Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将文件转换为字符串以C#格式转换为文件?_C#_File - Fatal编程技术网

如何将文件转换为字符串以C#格式转换为文件?

如何将文件转换为字符串以C#格式转换为文件?,c#,file,C#,File,我正在编写一个应用程序,它将一个文本格式的文件从一台机器发送到另一台机器。我使用了这段代码,但显然,由于编码的原因,重建的文件被破坏了 //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.Ge

我正在编写一个应用程序,它将一个文本格式的文件从一台机器发送到另一台机器。我使用了这段代码,但显然,由于编码的原因,重建的文件被破坏了

//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();
有没有办法将文件转换为字符串并返回到文件


注意:我想转换所有文件类型,而不仅仅是文本文件。

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

使用


我无法发现代码中的错误,但我建议您最好使用
StreamReader
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();

传递给
StreamWriter
构造函数的
false
参数表示如果文件存在,我们不希望附加到该文件。

代码没有错误。它可以很好地转换文本文件,但无法转换具有不同扩展名的文件(无法使用文本编辑器读取的文件、exp图像、可执行文件…),这些文件在重建时会损坏。
File.WriteAllBytes(filename, Convert.FromBase64String(content));
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();