我怎么能读得到,即使一个文件中的"另一进程&QUOT使用;例外?读得、进程、文件、我怎么能

2023-09-03 05:50:08 作者:说谎的目击者

在VB.NET或C#,我想读的是由另一程序使用(这一点,其实,我不能停止该程序或将停止写入文本的文本文件的内容文件,我想周期性地读出什么是目前在文本文件中的其他程序)

 昏暗strContents中作为字符串
    昏暗objReader作为的StreamReader
    objReader =新的StreamReader(FULLPATH)
    strContents的= objReader.ReadToEnd()
    objReader.Close()
 

在VB中的code是上面(一个C#的答案将被罚款以及),但是,因为它是被另一个它仍然抛出了IO异常的进程无法访问文件file.txt的处理。有没有解决办法在这种情况下?

解决方案

 的FileStream logFileStream =新的FileStream(C:\ test.txt的,FileMode.Open,FileAccess.Read,文件共享。读写);
StreamReader的logFileReader =新的StreamReader(logFileStream);

而(!logFileReader.EndOfStream)
{
    串线= logFileReader.ReadLine();
    //你的code在这里
}

// 清理
logFileReader.Close();
logFileStream.Close();
 
海纳百川下载器怎么用 海纳百川下载器使用方法

原始来源为code

In VB.NET or C#, I'm trying to read the contents of a text file that is in use by another program (that's the point, actually, I can't stop the program or it stops writing to the text file, and I want to periodically read out what is currently in the text file in another program)

    Dim strContents As String
    Dim objReader As StreamReader
    objReader = New StreamReader(FullPath)
    strContents = objReader.ReadToEnd()
    objReader.Close()

in VB the code is above (a C# answer would be fine as well), however, it still throws the IO exception "The process cannot access the file 'file.txt' because it is being used by another process." Are there any workarounds in this scenario?

解决方案

FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader logFileReader = new StreamReader(logFileStream);

while (!logFileReader.EndOfStream)
{
    string line = logFileReader.ReadLine();
    // Your code here
}

// Clean up
logFileReader.Close();
logFileStream.Close();

Original source for code