Comparing two strings from two different streams are never equal even though they should be
I have a stream that is reading the response from a site. I am then saving that stream to text in a text file.
If I then run it again and compare the string from the same site and the text saved in the file it thinks they are different.
When I compare the two strings in a diff tool like WinMerge it find differences at apparently identical points.
What is happening? They are both using the default UTF8 encoder.
I appreciate this may be difficult to follow so I have written a working example for you.
Here is an example:
var request = WebRequest.Create("http://www.google.com");
using (var response = request.GetResponse())
using (var body = response.GetResponseStream())
using (var googReader = new StreamReader(body))
using (var googFileStream = File.Open("goog.txt", FileMode.OpenOrCreate))
using (var fileReader = new StreamReader(googFileStream))
{
var googText = googReader.ReadToEnd();
var fileText = fileReader.ReadToEnd();
if (!string.Equals(googText, fileText))
{
googFileStream.Dispose();
using (var msnWriter = new StreamWriter(File.Open("goog.txt", FileMode.Create)))
{
msnWriter.Write(googText);
}
}
}
Here is the apparent 'difference' as reported b开发者_开发知识库y WinMerge. It is apparently at the point between html; charset:
Your code seems fine. It's just that Google
actually returns different contents every time you send a request to it. Other than that you might try simplifying your code and use a site which doesn't return different contents everytime:
var file = "goog.txt";
using (var client = new WebClient())
{
var data = client.DownloadString("http://www.google.com");
if (!File.Exists(file) || !string.Equals(File.ReadAllText(file), data))
{
File.WriteAllText(file, data);
}
}
精彩评论