Click here to Skip to main content
15,898,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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 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
Posted
Comments
Sinisa Hajnal 18-May-15 6:16am    
Simple. Don't use file. Write the entry into the database.

1 solution

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:
C#
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 );
 
          }
 
      }
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900