许多用户无法同时访问文本文件

问题描述:

我已经创建了一个文本文件,并使用c#添加页面名称,IP地址,页面引用。我使用这种方式来获取有多少用户访问我的网页。我的代码如下:



i have create a text file and add page name, ip address, page referrer using c#.I use this way to get how many user visit my webpage. my code is below:

public void createTextFile()
  {
      string path = @"D:\testFile.txt";
      // This text is added only once to the file.
      if (!File.Exists(path))
      {
          // Create a file to write to.
          string textSt = ipaddress+pagename;
          using (StreamWriter sw = File.CreateText(path))
          {
              sw.WriteLine(textSt );

          }
      }
      else
      {
          using (StreamWriter sw = File.AppendText(path))
          {
              sw.WriteLine(textSt );

          }

      }
  }





i调用上面的函数在page_load()函数中的每个页面中都有效。但是当许多用户同时点击同一页面时,此时会出现此问题进程无法访问该文件。我怎样才能解决这个问题



i call this above function in every page in page_load() function.it is working.but when many user hit the same page in same time, in that time this problem is shown "The process cannot access the file". how can i solve this problem

有2个解决方案。

第一个是使用File.Open并将FileMode设置为追加(该文件必须存在),FileShare设置为ReadWrite。

第二种是将文件访问与关键部分(锁定)联锁以避免并发访问:

There are 2 solutions.
The first is to use File.Open with FileMode set to append (the file must exist), and FileShare set to ReadWrite.
The second is to interlock the file access with a critical section (lock) to avoid concurrent access:
System.Object lockThis = new System.Object();

public void createTextFile()
{
  lock (lockThis)
  {
      string path = @"D:\testFile.txt";
      // This text is added only once to the file.
      if (!File.Exists(path))
      {
          // Create a file to write to.
          string textSt = ipaddress+pagename;
          using (StreamWriter sw = File.CreateText(path))
          {
              sw.WriteLine(textSt );
 
          }
      }
      else
      {
          using (StreamWriter sw = File.AppendText(path))
          {
              sw.WriteLine(textSt );
 
          }
 
      }
  }
}