看起来应该有比这更短的东西:
private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } }
Jimmy.. 17
首先,标题要求"如何将strnig的内容写入文本文件",但您的代码示例是"如何将文本文件的内容读取到字符串".
回答这两个问题:
using System.IO; ... string filename = "C:/example.txt"; string content = File.ReadAllText(filename); File.WriteAllText(filename, content);
另请参阅ReadAllLines/WriteAllLines和ReadAllBytes/WriteAllBytes,而不是您想要字符串数组或字节数组的字符串.
首先,标题要求"如何将strnig的内容写入文本文件",但您的代码示例是"如何将文本文件的内容读取到字符串".
回答这两个问题:
using System.IO; ... string filename = "C:/example.txt"; string content = File.ReadAllText(filename); File.WriteAllText(filename, content);
另请参阅ReadAllLines/WriteAllLines和ReadAllBytes/WriteAllBytes,而不是您想要字符串数组或字节数组的字符串.
string text = File.ReadAllText("c:\file1.txt"); File.WriteAllText("c:\file2.txt", text);
另请查看ReadAllLines/WriteAllLines和ReadAllBytes/WriteAllBytes