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

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

本文介绍了许多用户无法同时访问文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个文本文件,并使用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

推荐答案

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 );

          }

      }
  }
}


这篇关于许多用户无法同时访问文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:15