我想同时读取和写入文件。这行不通。
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"C:\words.txt");
StreamWriter sw = new StreamWriter(@"C:\words.txt");
}
如何在C#中读取和写入文件?
Answers:
您只需要打开一个流就可以同时进行阅读和写作。
FileStream fileStream = new FileStream(
@"c:\words.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
不要忘记简单的路线:
static void Main(string[] args)
{
var text = File.ReadAllText(@"C:\words.txt");
File.WriteAllText(@"C:\words.txt", text + "DERP");
}
您可以尝试执行以下操作:每次运行此代码时,都会在bin-> debug文件夹中自动创建“ Filename.txt”文件,也可以指定文件的路径,例如:@“ C:/ ...”。您可以通过转到bin-> debug文件夹来检查“ Hello”的存在性
PS不要忘记在此代码段之后添加Console.Readline(),否则不会出现控制台。
TextWriter tw = new StreamWriter("filename.txt");
String text = "Hello";
tw.WriteLine(text);
tw.Close();
TextReader tr = new StreamReader("filename.txt");
Console.WriteLine(tr.ReadLine());
tr.Close();
@Ipsita制作了一个改进代码-用于异步读写文件I / O
readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
TextReader tr = new StreamReader(logPath);
string data = await tr.ReadLineAsync();
tr.Close();
TextWriter tw = new StreamWriter(logPath);
await tw.WriteLineAsync(data + dataToWrite);
tw.Close();
}
...
await WriteToLogAsync("Write this to file");