-3

The process cannot access the file because it is being used by another process

private void DeleteReport()    
{
      int invid = Convert.ToInt32(Session["InvId"]);    
      string FileName = invid + "_Report" + ".pdf";    
      string path1 = Server.MapPath("~/Report/" + FileName);    
      if (File.Exists(path1))   
      {   
          File.Delete(path1);    
      }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Chethan Hr
  • 11
  • 1
  • 2
  • Is this problem occuring on your local machine or some remote server? Do you have this file opened in some reader, maybe? – semao Sep 18 '14 at 12:48
  • 2
    What you have posted here is a statement, not a question. So the file is in use, and you cannot delete it until that process releases the file handle. That's a fact and you can do nothing about it, except terminate that other process if it's under your control. – stakx - no longer contributing Sep 18 '14 at 12:50
  • In the method which calls DeleteReport(), you have something which use this file. Probably SqlConnection or something like this. You should Close() the Connection. You should show the method which calls DeleteReport. – mybirthname Sep 18 '14 at 13:03

1 Answers1

0

The error tells you, that the file is used and can't be deleted. So nothing wrong. As you did not formulate a real question, lets try to help you in following way.

I guess that only your program is using the report, so good possible, you block the report somewhere else.

E.g., the following code

string path = "C:\\Temp\\test.txt";
FileStream file = File.Open(path, FileMode.OpenOrCreate);
if (File.Exists(path))
  File.Delete(path);

raises the same error. It does not necessarily mean that the process is another process.

What you can do is for example, for testing purpose, install SysInternal http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx and add following code around your File.Delete statement. Then you will see, what process uses the file:

try
{
  File.Delete(path);
}
catch (Exception)
{
  using (Process tool = new Process())
  {
    tool.StartInfo.FileName = @"C:\Program Files (x86)\SysinternalsSuite\handle.exe"; //Your path
    tool.StartInfo.Arguments = path + " /accepteula";
    tool.StartInfo.UseShellExecute = false;
    tool.StartInfo.RedirectStandardOutput = true;
    tool.Start();
    tool.WaitForExit();
    string outputTool = tool.StandardOutput.ReadToEnd();

    string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
    foreach (Match match in Regex.Matches(outputTool, matchPattern))
    {
      Process p = Process.GetProcessById(int.Parse(match.Value));
      MessageBox.Show(p.ProcessName); // OR LOG IT
    }
  }

  throw;
}        

Credit for handle.exe call to https://stackoverflow.com/a/1263609/2707156

Community
  • 1
  • 1
StefanG
  • 1,234
  • 2
  • 22
  • 46