[英]How to access a text file in c# that is being used by another process
I have text file which is being been used by modscan to write data into the file. 我有一个文本文件,modscan正在使用该文本文件将数据写入该文件。 At a particular time I have to read the data and save in database. 在特定时间,我必须读取数据并保存在数据库中。 In offline mode ie; 在离线模式下 without modscan using it I can read the data and very well save in database. 无需使用modscan,我就可以读取数据并很好地保存在数据库中。 however as it online with modscan it gives exception 但是,因为它与modscan在线存在异常
Cannot access file as it been used by other process. 无法访问文件,因为该文件已被其他进程使用。
My code: 我的代码:
using System.IO;
string path = dt.Rows[i][11].ToString();
string[] lines = System.IO.File.ReadAllLines(@path);
path has "E:\\Metertxt\\02.txt"
路径具有"E:\\Metertxt\\02.txt"
So what changes I need to make in order to read it without interfering with modscan. 因此,在不干扰modscan的情况下,需要进行哪些更改才能读取它。 I googled and I found this which might work, however I am not sure how to use it 我用谷歌搜索,发现它可能有效,但是我不确定如何使用它
FileShare.ReadWrite FileShare.ReadWrite
You can use a FileStream
to open a file that is already open in another application. 您可以使用FileStream
打开在另一个应用程序中已经打开的文件。 Then you'll need a StreamReader
if you want to read it line by line. 然后,如果要逐行读取它,则需要一个StreamReader
。 This works, assuming a file encoding of UTF8: 假设文件编码为UTF8,此方法有效:
using (var stream = new FileStream(@"c:\tmp\locked.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with line, e.g. add to a list or whatever.
Console.WriteLine(line);
}
}
}
Alternative in case you really need a string[]
: 如果您确实需要一个string[]
:
var lines = new List<string>();
using (var stream = new FileStream(@"c:\tmp\locked.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
}
}
// Now you have a List<string>, which can be converted to a string[] if you really need one.
var stringArray = lines.ToArray();
FileStream fstream = new FileStream("@path", FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
StreamReader sreader = new StreamReader(fstream);
List<string> lines = new List<string>();
string line;
while((line = sreader.ReadeLine()) != null)
lines.Add(line);
//do something with the lines
//if you need all lines at once,
string allLines = sreader.ReadToEnd();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.