日期:2014-05-18  浏览次数:20787 次

请大家帮个忙,同时读写文件问题
我有两个C#winform程序,一个读文件,将文件里的内容一行行读出来上传到服务器,另一个程序写文件,隔一段时间写一次文件,将数据追加到文件末尾,这样就造成进程被占用的情况

请问该如何解决?

------解决方案--------------------
共享打开文件FileShare.ReadWrite
参考如下代码:
C# code
private void button1_Click(object sender, EventArgs e)
{
    FileStream vFileStream = new FileStream(@"c:\temp\temp.txt",
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    StreamReader vStreamReader = new StreamReader(vFileStream, Encoding.Default);
    Console.WriteLine(vStreamReader.ReadToEnd());
}
private FileStream writeStream = new FileStream(@"c:\temp\temp.txt",
    FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

private StreamWriter streamWriter;
private void button2_Click(object sender, EventArgs e)
{                    
    if (streamWriter == null)
        streamWriter = new StreamWriter(writeStream, Encoding.Default);
    streamWriter.WriteLine("Zswang路过");
    streamWriter.Flush();
}