2

I am writing an application that sends a file in text format from a machine to another i've used this code but apparently the reconstructed file is corrupted due to Encoding i think.

//file to String
byte[] bytes = System.IO.File.ReadAllBytes(filename);
string text = System.Text.Encoding.UTF8.GetString(bytes);

//String to file
byte[] byteArray = Encoding.UTF8.GetBytes(text);
FileStream ar = new FileStream("c:\\"+filename,System.IO.FileMode.Create);
ar.Write(byteArray, 0, byteArray.Length);
ar.Close();

Is there any way to convert a file to string and back to file?

Note: i want to convert all file types not only text files.

4

2 回答 2

5

将您的字节数组转换为 base64 字符串,然后在另一侧转换回字节数组。

利用

string content = Convert.ToBase64String(File.ReadAllBytes(filename));

File.WriteAllBytes(filename, Convert.FromBase64String(content));
于 2013-06-05T02:46:07.450 回答
1

我无法在您的代码中发现错误,但我建议您最好使用StreamReaderand StreamWriter

var reader = new System.IO.StreamReader(filePath, System.Text.Encoding.UTF8);
var text = reader.ReadToEnd();

reader.Close();

var writer = new System.IO.StreamWriter(filePath, false, System.Text.Encoding.UTF8);

writer.Write(text);
writer.Close();

false传递给构造函数的参数StreamWriter是表示如果文件存在,我们不想追加到文件中。

于 2013-06-05T02:56:39.783 回答