English 中文(简体)
我怎么能够读到一个文本文件,而不要把它锁起来?
原标题:How can I read a text file without locking it?
  • 时间:2010-08-10 11:03:19
  •  标签:
  • c#
  • file-io

我有一个窗口服务以简单格式在文本档案中书写其标识。

现在,我会制作一个小的应用程序,读到服务日志,并显示现有日志和新增的日志。

问题是,这项服务为增加新线路的文字文件打开了锁,同时,浏览器申请将文件锁定供阅读。

《服务法》:

void WriteInLog(string logFilePath, data)
{
    File.AppendAllText(logFilePath, 
                       string.Format("{0} : {1}
", DateTime.Now, data));
}

The viewer Code:

int index = 0;
private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                using (StreamReader sr = new StreamReader(logFilePath))
                {
                    while (sr.Peek() >= 0)  // reading the old data
                    {
                        AddLineToGrid(sr.ReadLine());
                        index++;
                    }
                    sr.Close();
                }

                timer1.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


private void timer1_Tick(object sender, EventArgs e)
        {
            using (StreamReader sr = new StreamReader(logFilePath))
            {
                // skipping the old data, it has read in the Form1_Load event handler
                for (int i = 0; i < index ; i++) 
                    sr.ReadLine();

                while (sr.Peek() >= 0) // reading the live data if exists
                {
                    string str = sr.ReadLine();
                    if (str != null)
                    {
                        AddLineToGrid(str);
                        index++;
                    }
                }
                sr.Close();
            }
        }

我的法典中是否有任何读写的问题?

如何解决这一问题?

最佳回答

你们需要确保,无论是服务还是读者,都无一例外地开放记录。 为此:

举例来说,这项服务使用的是:

var outStream = new FileStream(logfileName, FileMode.Open, 
                               FileAccess.Write, FileShare.ReadWrite);

阅读者使用相同但可更改文档存取:

var inStream = new FileStream(logfileName, FileMode.Open, 
                              FileAccess.Read, FileShare.ReadWrite);

此外,自<代码>FileStream 实施IDisposable以来,确保在上述两种情况下,您均考虑使用<>代码>(<<>>>,例如,作者:

using(var outStream = ...)
{
   // using outStream here
   ...
}

亲爱!

问题回答

在阅读文本档案时,明确确定了共享模式。

using (FileStream fs = new FileStream(logFilePath, 
                                      FileMode.Open, 
                                      FileAccess.Read,    
                                      FileShare.ReadWrite))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        while (sr.Peek() >= 0) // reading the old data
        {
           AddLineToGrid(sr.ReadLine());
           index++;
        }
    }
}
new StreamReader(File.Open(logFilePath, 
                           FileMode.Open, 
                           FileAccess.Read, 
                           FileShare.ReadWrite))

- &;这 t锁了档案。

问题是,在你写给你时,你只把卷宗锁定下来,以便让你精炼的Reader打开。

你们需要尝试在上开放文件。

using (FileStream fs = new FileStream("myLogFile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        while (!fs.EndOfStream)
        {
            string line = fs.ReadLine();
            // Your code here
        }
    }
}

我记得几年前也做了同样的事。 在进行了一些gogle查询之后,发现:

    FileStream fs = new FileStream(@”c:	est.txt”, 
                                   FileMode.Open, 
                                   FileAccess.Read,        
                                   FileShare.ReadWrite);

i.e. 在FileStream()上使用档案库。

(见Balaji Ramesh s blog )

您是否尝试复制档案,然后阅读?

每当作重大改动时,仅更新复印件。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...