开发者

Can we compare two JavaScript files using C#?

I have tried comparing two text files. If these contain the same data but there is a difference of even one space the result is showing as ‘different’.

Can anyone tell me how to compare two JavaSc开发者_StackOverflow中文版ript files using C#?


Since JavaScript is whitespace tolerant (tolerates any amount of whitespace as long as the syntax is correct), the simplest thing to do if you want to compare everything but the whitespace is to regex-replace:

Regex _r = new Regex(@"\s+", RegexOptions.Compiled);
string result = _r.Replace(value, " ");

Run this on both files and compare the results; it replaces any sequence of standard whitespace characters (space, tab, carriage return, vertical tab etc.) with a single space. You can then compare with Equals (case sensitive or not, as you require).

Of course, whitespace IS significant inside strings, so this assumes the string handling in all the compared files does not rely on whitespace too much.

However two very different code files can have the same effects, so if that's what you're after you have a hard job ahead of you.


Do you just need to know if they are exactly the same? If so you could just load them into memory and compare the .length() property...


Technically, if one file contains an extra space they aren't "the same". I would first compare the lengths and if those don't match you'll need to do a byte by byte comparison. If you want to remove extra spaces you'll probably want to do something like a Trim() on the contents of both files first.

Here's a link to an old MS post describing how to create a file compare function:

http://support.microsoft.com/kb/320348

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜