?
Solved

File Locking/Acccess help when copying and deleteing

Posted on 2004-09-08
8
Medium Priority
?
1,977 Views
Last Modified: 2012-06-27

When using the FileInfo object I am trying to copy files from one folder to another. After the copy process is complete, I delete the file in the original folder.  After viewing the logs I see this error every once in awhile.

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

I have tried numerous pieces of code (GC.collect, fi.refresh, checking for the file being locked, etc ...) and I still get this error and even more frequently.  Here is some of the code.  The project is a windows service.

private void fsw_Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
            {
                  
                  FileInfo fi = new FileInfo(e.FullPath);      
                  fi.Refresh();
                  if(!fi.Exists) return;      

                  try
                  {
                        string trans_id = this.MakeTransactionID();                                                
                        this.LogReceiptOfFile(fi.Name,trans_id);                  
                        
                        if(fi.Name!="heartbeat.csv")
                        {
                              fi.Refresh();
                              this.CopyToArchive(fi,trans_id);
                        }                        
                        fi.Refresh();
                        this.CopyToOut(fi,trans_id);      
                        fi.Refresh();
                        this.DeleteFromIn(fi,trans_id);
                  }
                  catch(Exception ex)
                  {
                        this.LogError("fsw_Watcher_Changed",ex);
                  }
                  finally
                  {
                        fi = null;
                        GC.Collect();
                  }
            }

            private void LogReceiptOfFile(string fileName,string trans_id)
            {
                  Log myLog = new Log(LOGPATH);
                  myLog.WriteToProcessLog(trans_id,1,"Received","MCGWare",fileName);
                  myLog = null;
            }

            private void LogError(string func,Exception ex)
            {
                  Log myLog = new Log(LOGPATH);
                  myLog.WriteLogMessage(func,ex.Message + "\n" + ex.StackTrace,1);
                  myLog = null;

                  EventLog elog = new EventLog();
                  elog.Source = "Application";
                  elog.Log = "Application";
                  elog.WriteEntry("Error reported in fsw_Watcher_Changed function. Read SDX log files for details.",
                        System.Diagnostics.EventLogEntryType.Error);      
                  elog = null;
            }

            private void CopyToArchive(FileInfo fi,string trans_id)
            {
                  Log myLog = new Log(this.processPath);
                  string fileName =
                        this.archivePath + "\\" +
                        this.MakeFileName(fi.Name.Replace(".csv",""));                  
                  try
                  {
                        fi.CopyTo(fileName,true);
                        myLog.WriteToProcessLog(trans_id,1,"Copy",fi.FullName,fileName);
                  }
                  catch(Exception ex)
                  {
                        this.LogError("CopyToArchive",ex);
                        myLog.WriteToProcessLog(trans_id,0,"Copy",fi.FullName,fileName);
                  }
                  finally
                  {
                        myLog = null;
                  }
            }

            private void CopyToOut(FileInfo fi,string trans_id)
            {
                  Log myLog = new Log(this.processPath);
                  string fileName = this.outPath + "\\" + fi.Name;
                  try
                  {
                        fi.CopyTo(fileName,true);
                        myLog.WriteToProcessLog(trans_id,1,"Copy",fi.FullName,fileName);
                  }
                  catch(Exception ex)
                  {
                        this.LogError("CopyToOut",ex);
                        myLog.WriteToProcessLog(trans_id,0,"Copy",fi.FullName,fileName);
                  }
                  finally
                  {
                        myLog = null;
                  }
            }

            private void DeleteFromIn(FileInfo fi,string trans_id)
            {
                  Log myLog = new Log(this.processPath);
                  try
                  {
                        fi.Delete();
                        myLog.WriteToProcessLog(trans_id,1,"Delete",fi.FullName,"");
                  }
                  catch(Exception ex)
                  {
                        this.LogError("DeleteFromIn",ex);
                        myLog.WriteToProcessLog(trans_id,0,"Delete",fi.FullName,"");
                  }
                  finally
                  {
                        myLog = null;
                  }
            }
0
Comment
Question by:pjbaratelli
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 12010124
it can be another process aside from your own who is locking the file (i.e. has it open).
0
 
LVL 1

Author Comment

by:pjbaratelli
ID: 12010322
Yeah, but how can you check to see if the file is locked? I have used this code to test.

            private bool IsLocked(FileInfo fi)
            {
                  bool locked = false;
                  try
                  {
                        fi.Open(FileMode.Open,FileAccess.Read,FileShare.None);
                  }
                  catch
                  {
                        locked = true;
                  }
                  return locked;
            }

Is there another way? This one didn't seem to work.
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 12010429
no and that way doesnt really work because I could say ...

if(!IsLocked(@"C:\foo.bar")) {
    //another process opens file here ...
    File.Open ....
}
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:pjbaratelli
ID: 12010452
How could you do it then? That was an example I got off a web site in desperation.  Is there an attribute that I should be looking at?
0
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 1000 total points
ID: 12010493
no .. you need to handle the case that it may fail ... remember its another process that may be opening your file there is no way of reliably handling it.
0
 
LVL 1

Author Comment

by:pjbaratelli
ID: 12011707
What would be a good process flow to follow? Three tries and then send an alert to someone of failure?  Should I wait so many seconds before each try? The object is to get it so that these files get to where there going 100% if the time.  Where programatically or manually.
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 12011720
I would put a 2-3 second Thread.Sleep in between ...

0
 
LVL 1

Author Comment

by:pjbaratelli
ID: 12020359
Okay, this worked great.   My boss is a happy.  Thanks Greg.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses
Course of the Month14 days, 12 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question