Reputation: 993
If I read and wrote a binary file using StreamReader and StreamWriter, can the file be repaired?
// Original Code - Corrupted the Destination File
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
using (StreamWriter writer = new StreamWriter(destinationFileName, false))
{
writer.Write(reader.ReadToEnd());
}
}
}
// New Code - Destination File is Good
using (Stream responseStream = response.GetResponseStream())
{
using (FileStream fs = File.Create(destinationFileName))
{
responseStream.CopyTo(fs);
}
}
Upvotes: 2
Views: 2313
Reputation: 171178
Try to read it with a StreamReader and see if the string you get back makes sense. This is your best option to recover the data. Once you have a "correct" string you need to try different Encodings to write to a binary file. Try UTF8, UTF16 and Encoding.Default.
I guess it will take a bit of playing around to recover some of the data. Please note that it is likely that you have lost some of it permanently.
Upvotes: 0
Reputation: 1500515
If I read and wrote a binary file using StreamReader and StreamWriter, can the file be repaired?
It depends what's in the file. If it's actually text in the right encoding, then you won't have lost anything.
If it's genuinely binary data (e.g. a JPEG) then you'll almost certainly have lost information, irreparably. Just don't do it, and if you've already done it, I probably wouldn't try to "fix" the files - I'd write them off as "bad".
If you'd used ISO-8859-1, it's possible that all would have been well - although it would still have been bad code which would be better off changed.
Upvotes: 3