"Process cannot access file" problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul

    "Process cannot access file" problem

    Hi,
    VB.NET is saying the file I am creating is in use by another process and
    won't complete its task of moving the file to the specified destination
    folder.
    Here is my code (the main bit anyway)....


    Private Sub LogChange(ByVal source As Object, ByVal e As
    System.IO.FileS ystemEventArgs)
    If e.ChangeType = WatcherChangeTy pes.Created Then
    System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
    End If


    e.FullPath returns the full path and filename of the file created e.g
    c:\filename.txt
    textboxDest is where the file is to be moved to e.g D:\
    e.Name is the filename without the path e.g. filename.txt

    This is the error text...

    System.IO.IOExc eption: The process cannot access the file
    "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
    What happens is files get downloaded to the D:\Unsorted\ folder which is
    being monitored by the FileSystemWatch er. The app then tries to move the
    downloaded/created file to the D:\Unsorted\200 5\ folder then the error
    occurs.

    Any help much appreciated,
    Thanks
    Paul


  • petterl

    #2
    Re: "Proces s cannot access file" problem

    I had simular problems with my filewatch program. It happend when I had a
    window open on that directory in thumbnail or filmstrip mode. I also got a
    tip about check if the file is finished before move it. try opend the file.
    I have not tested the tip yet.

    Petter L

    "Paul" <private@mail.c om> wrote in message
    news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=blue]
    > Hi,
    > VB.NET is saying the file I am creating is in use by another process and
    > won't complete its task of moving the file to the specified destination
    > folder.
    > Here is my code (the main bit anyway)....
    >
    >
    > Private Sub LogChange(ByVal source As Object, ByVal e As
    > System.IO.FileS ystemEventArgs)
    > If e.ChangeType = WatcherChangeTy pes.Created Then
    > System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
    > End If
    >
    >
    > e.FullPath returns the full path and filename of the file created e.g
    > c:\filename.txt
    > textboxDest is where the file is to be moved to e.g D:\
    > e.Name is the filename without the path e.g. filename.txt
    >
    > This is the error text...
    >
    > System.IO.IOExc eption: The process cannot access the file
    > "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
    > What happens is files get downloaded to the D:\Unsorted\ folder which is
    > being monitored by the FileSystemWatch er. The app then tries to move the
    > downloaded/created file to the D:\Unsorted\200 5\ folder then the error
    > occurs.
    >
    > Any help much appreciated,
    > Thanks
    > Paul
    >[/color]


    Comment

    • petterl

      #3
      Re: &quot;Proces s cannot access file&quot; problem

      Hi again

      Right after my first nessage I got the problem again in my program. When I
      halted right before the copy action and steped though it, it worked most of
      the times but if i let the program run it created a "Process cannot access
      file" and it pointed to the destination path for the file. What i did was to
      put

      System.Threadin g.Thread.Sleep( 5000)

      before the copy routine and now it works fine.

      Maybe this can help on your problem too ?

      Petter L.

      "Paul" <private@mail.c om> wrote in message
      news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=blue]
      > Hi,
      > VB.NET is saying the file I am creating is in use by another process and
      > won't complete its task of moving the file to the specified destination
      > folder.
      > Here is my code (the main bit anyway)....
      >
      >
      > Private Sub LogChange(ByVal source As Object, ByVal e As
      > System.IO.FileS ystemEventArgs)
      > If e.ChangeType = WatcherChangeTy pes.Created Then
      > System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
      > End If
      >
      >
      > e.FullPath returns the full path and filename of the file created e.g
      > c:\filename.txt
      > textboxDest is where the file is to be moved to e.g D:\
      > e.Name is the filename without the path e.g. filename.txt
      >
      > This is the error text...
      >
      > System.IO.IOExc eption: The process cannot access the file
      > "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
      > What happens is files get downloaded to the D:\Unsorted\ folder which is
      > being monitored by the FileSystemWatch er. The app then tries to move the
      > downloaded/created file to the D:\Unsorted\200 5\ folder then the error
      > occurs.
      >
      > Any help much appreciated,
      > Thanks
      > Paul
      >[/color]


      Comment

      • Paul

        #4
        Re: &quot;Proces s cannot access file&quot; problem

        Thanks for the tip Petter. It works on my problem too but I would prefer to
        use a better way if one is known.

        Is it possible to lock the file being moved so that no other process can
        access the file? E.g. Windows trying to extract thumbnail, ID3 tag etc.

        Thanks,
        Paul



        "petterl" <petterathome@h otmail.com> wrote in message
        news:u2l6fdK9EH A.2180@TK2MSFTN GP12.phx.gbl...[color=blue]
        > Hi again
        >
        > Right after my first nessage I got the problem again in my program. When I
        > halted right before the copy action and steped though it, it worked most
        > of the times but if i let the program run it created a "Process cannot
        > access file" and it pointed to the destination path for the file. What i
        > did was to put
        >
        > System.Threadin g.Thread.Sleep( 5000)
        >
        > before the copy routine and now it works fine.
        >
        > Maybe this can help on your problem too ?
        >
        > Petter L.
        >
        > "Paul" <private@mail.c om> wrote in message
        > news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=green]
        >> Hi,
        >> VB.NET is saying the file I am creating is in use by another process and
        >> won't complete its task of moving the file to the specified destination
        >> folder.
        >> Here is my code (the main bit anyway)....
        >>
        >>
        >> Private Sub LogChange(ByVal source As Object, ByVal e As
        >> System.IO.FileS ystemEventArgs)
        >> If e.ChangeType = WatcherChangeTy pes.Created Then
        >> System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
        >> End If
        >>
        >>
        >> e.FullPath returns the full path and filename of the file created e.g
        >> c:\filename.txt
        >> textboxDest is where the file is to be moved to e.g D:\
        >> e.Name is the filename without the path e.g. filename.txt
        >>
        >> This is the error text...
        >>
        >> System.IO.IOExc eption: The process cannot access the file
        >> "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
        >> What happens is files get downloaded to the D:\Unsorted\ folder which is
        >> being monitored by the FileSystemWatch er. The app then tries to move the
        >> downloaded/created file to the D:\Unsorted\200 5\ folder then the error
        >> occurs.
        >>
        >> Any help much appreciated,
        >> Thanks
        >> Paul
        >>[/color]
        >
        >[/color]


        Comment

        • Tom Krueger [MSFT]

          #5
          Re: &quot;Proces s cannot access file&quot; problem

          Hello,

          I'm not sure if you are running into the same issue I had a while back or
          not, but just incase here are my thoughts.

          I remember I would get the same error and the only way I could get around it
          was by calling dispose on the FileSystemWatch er. Here are my notes from the
          code I wrote a while back
          /// Release handles to directory. A directory cannot be fully
          /// deleted until it is released. Need to use Dispose because
          /// can't wait for garbage collector.

          It worked for me. So I my architectured was a class called
          FileSystemMonit er (which I created) and in this class I setup the
          FileSystemWatch er and exposed the events of FileSystemWatch er. Mine might
          be a bit different in that for each FileSystemWatch er event I had them raise
          a my own Changed event so that my subscribers only had to listen to one
          event when any changes occured.

          Then when I needed to start and stop watching I released the references to
          the changed event and called dispose on the FileSystemMonit or. Here is some
          of the code.


          /// <summary>

          /// Monitors the file system for any changes in the specified path.

          /// </summary>

          public class FileSystemMonit or : IDisposable {


          # region ***** FIELDS *****

          private int _ignoreChangesP eriod;

          private int _lastChangeTime ;

          private FileSystemWatch er _watcher;

          private FileSystemWatch er _watcherChanged ;

          private string _watchPath;

          public delegate void FileSystemChang edHandler(objec t sender,
          FileSystemEvent Args e);

          public event FileSystemChang edHandler Changed;

          # endregion

          # region ***** CONSTRUCTORS *****

          public FileSystemMonit or(string path) {

          _watchPath = path;

          _watcher = new FileSystemWatch er();

          _watcher.Create d += new FileSystemEvent Handler(OnFileC reated);

          _watcher.Delete d += new FileSystemEvent Handler(OnFileD eleted);

          _watcher.Rename d += new RenamedEventHan dler(OnFileRena med); // NOTE: THIS
          MAY NOT BE WORKING.

          SetWatcherPrope rties(_watcher) ;

          // Setup second watcher to watch changed because

          // Create, Delete, and rename don't seem to fire when NotifyFilter is set.

          // NOTE: THIS MAY NOT BE WORKING.

          _watcherChanged = new FileSystemWatch er();

          _watcherChanged .Changed += new FileSystemEvent Handler(OnFileC hanged);

          _watcherChanged .NotifyFilter = NotifyFilters.F ileName |
          NotifyFilters.D irectoryName;

          SetWatcherPrope rties(_watcherC hanged);

          }

          # endregion

          # region ***** PUBLIC METHODS *****

          /// <summary>

          /// Release handles to directory. A directory cannot be fully

          /// deleted until it is released. Need to use Dispose because

          /// can't wait for garbage collector.

          /// </summary>

          public void Dispose() {

          _watcher.Dispos e();

          _watcherChanged .Dispose();

          }

          # endregion

          # region ***** PRIVATE METHODS *****

          private void SetWatcherPrope rties(FileSyste mWatcher watcher) {

          watcher.Path = _watchPath;

          watcher.Filter = "*.*";

          watcher.Include Subdirectories = true;

          watcher.EnableR aisingEvents = true;

          }

          private void OnFileCreated(o bject sender, FileSystemEvent Args e) {

          Debug.WriteLine ("FileSystmeMon itor.OnFileCrea ted: " + e.FullPath);

          CallChanged(sen der, e);

          }

          private void OnFileDeleted(o bject sender, FileSystemEvent Args e) {

          Debug.WriteLine ("FileSystmeMon itor.OnFileDele ted: " + e.FullPath);

          CallChanged(sen der, e);

          }

          private void OnFileRenamed(o bject sender, RenamedEventArg s e) {

          Debug.WriteLine ("FileSystmeMon itor.OnFileRena med: " + e.FullPath);

          CallChanged(sen der, e);

          }

          private void OnFileChanged(o bject sender, FileSystemEvent Args e) {

          Debug.WriteLine ("FileSystmeMon itor.OnFileChan ged: " + e.FullPath);

          CallChanged(sen der, e);

          }

          private void CallChanged(obj ect sender, FileSystemEvent Args e) {


          // Check if should ignore change.

          int currentTime = System.Environm ent.TickCount;

          if (currentTime - _lastChangeTime > _ignoreChangesP eriod) {

          if (this.Changed != null) {

          this.Changed(se nder, e);

          }

          } else {

          Debug.WriteLine ("CallChange d Ignored");

          }

          _lastChangeTime = currentTime;

          }

          # endregion

          #region ***** PROPERTIES *****

          public int IgnoreChangesMi liseconds {

          get { return _ignoreChangesP eriod; }

          set { _ignoreChangesP eriod = value; }

          }

          #endregion

          }



          -----

          These methods were in another class that was using The FileSystemMonit or.

          public void StartFileMonito r() {


          Debug.WriteLine ("Start File Monitor: " + this.Directory) ;

          // Setup file system monitor. This object will alert

          // this image to reload when changes occur to the file system.

          if (_fileSystemMon itor == null) {

          _fileSystemMoni tor = new FileSystemMonit or(_dirPath);

          _fileSystemMoni tor.IgnoreChang esMiliseconds =
          AppManager.FILE _SYSTEM_IGNORE_ CHANGES_TIME;

          }

          if (_fileSystemCha ngedHandler == null) {

          _fileSystemChan gedHandler = new
          FileSystemMonit or.FileSystemCh angedHandler(Fi leSystemMonitor _OnFileSystemCh anged);

          Debug.WriteLine ("FileSystemHan dler Created: " + this.Directory) ;

          }


          _fileSystemMoni tor.Changed += _fileSystemChan gedHandler;

          Debug.WriteLine ("FileSystemHan dler Added: " + this.Directory) ;

          }

          public void StopFileMonitor () {

          Debug.WriteLine ("Stoping File Monitor: " + this.Directory) ;

          // Remove event handler;

          if (_fileSystemCha ngedHandler != null) {

          _fileSystemMoni tor.Changed -= _fileSystemChan gedHandler;

          Debug.WriteLine ("FileSystemCha ngedHandler Removed: " + this.Directory) ;


          }

          if (_fileSystemMon itor != null) {

          _fileSystemMoni tor.Dispose();

          Debug.WriteLine ("FileSystemMon itor Disposed");

          //_fileSystemMoni tor = null;

          }

          }



          Hope that helps.




          --
          Tom Krueger

          Smart Client DevCenter - http://msdn.microsoft.com/smartclient/
          Mobile DevCenter - http://msdn.microsoft.com/mobility

          This posting is provided "as is" with no warranties and confers no rights.

          "Paul" <private@mail.c om> wrote in message
          news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=blue]
          > Hi,
          > VB.NET is saying the file I am creating is in use by another process and
          > won't complete its task of moving the file to the specified destination
          > folder.
          > Here is my code (the main bit anyway)....
          >
          >
          > Private Sub LogChange(ByVal source As Object, ByVal e As
          > System.IO.FileS ystemEventArgs)
          > If e.ChangeType = WatcherChangeTy pes.Created Then
          > System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
          > End If
          >
          >
          > e.FullPath returns the full path and filename of the file created e.g
          > c:\filename.txt
          > textboxDest is where the file is to be moved to e.g D:\
          > e.Name is the filename without the path e.g. filename.txt
          >
          > This is the error text...
          >
          > System.IO.IOExc eption: The process cannot access the file
          > "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
          > What happens is files get downloaded to the D:\Unsorted\ folder which is
          > being monitored by the FileSystemWatch er. The app then tries to move the
          > downloaded/created file to the D:\Unsorted\200 5\ folder then the error
          > occurs.
          >
          > Any help much appreciated,
          > Thanks
          > Paul
          >[/color]


          Comment

          • Petter L

            #6
            Re: &quot;Proces s cannot access file&quot; problem

            I found out it whas not a perfect solution but it worked on small files but
            big files it came back. So I looking into the other tip here also

            Petter L.
            "Paul" <private@mail.c om> wrote in message
            news:41de9bf1$0 $105$65c69314@m ercury.nildram. net...[color=blue]
            > Thanks for the tip Petter. It works on my problem too but I would prefer
            > to use a better way if one is known.
            >
            > Is it possible to lock the file being moved so that no other process can
            > access the file? E.g. Windows trying to extract thumbnail, ID3 tag etc.
            >
            > Thanks,
            > Paul
            >
            >
            >
            > "petterl" <petterathome@h otmail.com> wrote in message
            > news:u2l6fdK9EH A.2180@TK2MSFTN GP12.phx.gbl...[color=green]
            >> Hi again
            >>
            >> Right after my first nessage I got the problem again in my program. When
            >> I halted right before the copy action and steped though it, it worked
            >> most of the times but if i let the program run it created a "Process
            >> cannot access file" and it pointed to the destination path for the file.
            >> What i did was to put
            >>
            >> System.Threadin g.Thread.Sleep( 5000)
            >>
            >> before the copy routine and now it works fine.
            >>
            >> Maybe this can help on your problem too ?
            >>
            >> Petter L.
            >>
            >> "Paul" <private@mail.c om> wrote in message
            >> news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=darkred]
            >>> Hi,
            >>> VB.NET is saying the file I am creating is in use by another process and
            >>> won't complete its task of moving the file to the specified destination
            >>> folder.
            >>> Here is my code (the main bit anyway)....
            >>>
            >>>
            >>> Private Sub LogChange(ByVal source As Object, ByVal e As
            >>> System.IO.FileS ystemEventArgs)
            >>> If e.ChangeType = WatcherChangeTy pes.Created Then
            >>> System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
            >>> End If
            >>>
            >>>
            >>> e.FullPath returns the full path and filename of the file created e.g
            >>> c:\filename.txt
            >>> textboxDest is where the file is to be moved to e.g D:\
            >>> e.Name is the filename without the path e.g. filename.txt
            >>>
            >>> This is the error text...
            >>>
            >>> System.IO.IOExc eption: The process cannot access the file
            >>> "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
            >>> What happens is files get downloaded to the D:\Unsorted\ folder which is
            >>> being monitored by the FileSystemWatch er. The app then tries to move
            >>> the downloaded/created file to the D:\Unsorted\200 5\ folder then the
            >>> error occurs.
            >>>
            >>> Any help much appreciated,
            >>> Thanks
            >>> Paul
            >>>[/color]
            >>
            >>[/color]
            >
            >[/color]


            Comment

            • Petter L

              #7
              Re: &quot;Proces s cannot access file&quot; problem

              I found out it whas not a perfect solution but it worked on small files but
              big files it came back. So I looking into the other tip here also

              Petter L.
              "Paul" <private@mail.c om> wrote in message
              news:41de9bf1$0 $105$65c69314@m ercury.nildram. net...[color=blue]
              > Thanks for the tip Petter. It works on my problem too but I would prefer
              > to use a better way if one is known.
              >
              > Is it possible to lock the file being moved so that no other process can
              > access the file? E.g. Windows trying to extract thumbnail, ID3 tag etc.
              >
              > Thanks,
              > Paul
              >
              >
              >
              > "petterl" <petterathome@h otmail.com> wrote in message
              > news:u2l6fdK9EH A.2180@TK2MSFTN GP12.phx.gbl...[color=green]
              >> Hi again
              >>
              >> Right after my first nessage I got the problem again in my program. When
              >> I halted right before the copy action and steped though it, it worked
              >> most of the times but if i let the program run it created a "Process
              >> cannot access file" and it pointed to the destination path for the file.
              >> What i did was to put
              >>
              >> System.Threadin g.Thread.Sleep( 5000)
              >>
              >> before the copy routine and now it works fine.
              >>
              >> Maybe this can help on your problem too ?
              >>
              >> Petter L.
              >>
              >> "Paul" <private@mail.c om> wrote in message
              >> news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=darkred]
              >>> Hi,
              >>> VB.NET is saying the file I am creating is in use by another process and
              >>> won't complete its task of moving the file to the specified destination
              >>> folder.
              >>> Here is my code (the main bit anyway)....
              >>>
              >>>
              >>> Private Sub LogChange(ByVal source As Object, ByVal e As
              >>> System.IO.FileS ystemEventArgs)
              >>> If e.ChangeType = WatcherChangeTy pes.Created Then
              >>> System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
              >>> End If
              >>>
              >>>
              >>> e.FullPath returns the full path and filename of the file created e.g
              >>> c:\filename.txt
              >>> textboxDest is where the file is to be moved to e.g D:\
              >>> e.Name is the filename without the path e.g. filename.txt
              >>>
              >>> This is the error text...
              >>>
              >>> System.IO.IOExc eption: The process cannot access the file
              >>> "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
              >>> What happens is files get downloaded to the D:\Unsorted\ folder which is
              >>> being monitored by the FileSystemWatch er. The app then tries to move
              >>> the downloaded/created file to the D:\Unsorted\200 5\ folder then the
              >>> error occurs.
              >>>
              >>> Any help much appreciated,
              >>> Thanks
              >>> Paul
              >>>[/color]
              >>
              >>[/color]
              >
              >[/color]


              Comment

              • Bjarke Lindberg

                #8
                Re: &quot;Proces s cannot access file&quot; problem

                Petter L wrote:
                [color=blue]
                > I found out it whas not a perfect solution but it worked on small files but
                > big files it came back. So I looking into the other tip here also[/color]

                Hi Petter.

                I've had the same problem. My solution was something like this:

                /// <summary>
                /// This method returns as soon as the specified file is writeable.
                /// </summary>
                /// <param name="fileName" >The full path to the file.</param>
                protected void waitForFile(str ing fileName) {
                new FileWaiter(file Name).DoWait();
                }

                [...]
                internal class FileWaiter {
                public string fileName;

                public FileWaiter(stri ng fileName) {
                this.fileName = fileName;
                }

                public void DoWait(int timeout) {
                DoWait(new TimeSpan(0, 0, 0, 0, timeout));
                }

                public void DoWait() {
                DoWait(TimeSpan .MinValue);
                }

                public void DoWait(TimeSpan timeout) {
                System.Diagnost ics.Debug.Asser t(filename != null);
                Thread t = new Thread(new ThreadStart(Thr eadWait));
                t.Start();
                if (timeout > TimeSpan.MinVal ue)
                t.Join(timeout) ;
                else
                t.Join();
                }

                void ThreadWait() {
                do {
                //Start waiting..
                Thread.Sleep(50 0);
                }
                while (System.IO.File .Exists(fileNam e) && isFileOpen(file Name));
                }
                }

                protected static bool isFileOpen(stri ng fileName) {
                System.IO.FileS tream s = null;
                try {
                s = System.IO.File. Open(fileName, System.IO.FileM ode.Open,
                System.IO.FileA ccess.ReadWrite ,
                System.IO.FileS hare.None);
                return false;
                } catch (System.IO.IOEx ception) {
                return true;
                } finally {
                if (s != null)
                s.Close();
                }
                }
                [...]

                Comment

                • Bjarke Lindberg

                  #9
                  Re: &quot;Proces s cannot access file&quot; problem

                  Petter L wrote:
                  [color=blue]
                  > I found out it whas not a perfect solution but it worked on small files but
                  > big files it came back. So I looking into the other tip here also[/color]

                  Hi Petter.

                  I've had the same problem. My solution was something like this:

                  /// <summary>
                  /// This method returns as soon as the specified file is writeable.
                  /// </summary>
                  /// <param name="fileName" >The full path to the file.</param>
                  protected void waitForFile(str ing fileName) {
                  new FileWaiter(file Name).DoWait();
                  }

                  [...]
                  internal class FileWaiter {
                  public string fileName;

                  public FileWaiter(stri ng fileName) {
                  this.fileName = fileName;
                  }

                  public void DoWait(int timeout) {
                  DoWait(new TimeSpan(0, 0, 0, 0, timeout));
                  }

                  public void DoWait() {
                  DoWait(TimeSpan .MinValue);
                  }

                  public void DoWait(TimeSpan timeout) {
                  System.Diagnost ics.Debug.Asser t(filename != null);
                  Thread t = new Thread(new ThreadStart(Thr eadWait));
                  t.Start();
                  if (timeout > TimeSpan.MinVal ue)
                  t.Join(timeout) ;
                  else
                  t.Join();
                  }

                  void ThreadWait() {
                  do {
                  //Start waiting..
                  Thread.Sleep(50 0);
                  }
                  while (System.IO.File .Exists(fileNam e) && isFileOpen(file Name));
                  }
                  }

                  protected static bool isFileOpen(stri ng fileName) {
                  System.IO.FileS tream s = null;
                  try {
                  s = System.IO.File. Open(fileName, System.IO.FileM ode.Open,
                  System.IO.FileA ccess.ReadWrite ,
                  System.IO.FileS hare.None);
                  return false;
                  } catch (System.IO.IOEx ception) {
                  return true;
                  } finally {
                  if (s != null)
                  s.Close();
                  }
                  }
                  [...]

                  Comment

                  • Paul

                    #10
                    Re: &quot;Proces s cannot access file&quot; problem

                    I appreciate the code guys and the time spent replying but I'm afraid I
                    don't have a clue on how introduce any of it into my project as the two
                    examples posted have been in C as opposed to VB. I just realised I posted
                    this in the the dotnet.general NG aswell as the donet.languages .vb NG which
                    I suppose is why I got replies in C!
                    Sorry for the mistake. I guess I'll keep on looking!

                    Cheers,
                    Paul



                    "Tom Krueger [MSFT]" <a-tkrueg@online.m icrosoft.com> wrote in message
                    news:uVfLPZN9EH A.4028@TK2MSFTN GP15.phx.gbl...[color=blue]
                    > Hello,
                    >
                    > I'm not sure if you are running into the same issue I had a while back or
                    > not, but just incase here are my thoughts.
                    >
                    > I remember I would get the same error and the only way I could get around
                    > it was by calling dispose on the FileSystemWatch er. Here are my notes
                    > from the code I wrote a while back
                    > /// Release handles to directory. A directory cannot be fully
                    > /// deleted until it is released. Need to use Dispose because
                    > /// can't wait for garbage collector.
                    >
                    > It worked for me. So I my architectured was a class called
                    > FileSystemMonit er (which I created) and in this class I setup the
                    > FileSystemWatch er and exposed the events of FileSystemWatch er. Mine might
                    > be a bit different in that for each FileSystemWatch er event I had them
                    > raise a my own Changed event so that my subscribers only had to listen to
                    > one event when any changes occured.
                    >
                    > Then when I needed to start and stop watching I released the references to
                    > the changed event and called dispose on the FileSystemMonit or. Here is
                    > some of the code.
                    >
                    >
                    > /// <summary>
                    >
                    > /// Monitors the file system for any changes in the specified path.
                    >
                    > /// </summary>
                    >
                    > public class FileSystemMonit or : IDisposable {
                    >
                    >
                    > # region ***** FIELDS *****
                    >
                    > private int _ignoreChangesP eriod;
                    >
                    > private int _lastChangeTime ;
                    >
                    > private FileSystemWatch er _watcher;
                    >
                    > private FileSystemWatch er _watcherChanged ;
                    >
                    > private string _watchPath;
                    >
                    > public delegate void FileSystemChang edHandler(objec t sender,
                    > FileSystemEvent Args e);
                    >
                    > public event FileSystemChang edHandler Changed;
                    >
                    > # endregion
                    >
                    > # region ***** CONSTRUCTORS *****
                    >
                    > public FileSystemMonit or(string path) {
                    >
                    > _watchPath = path;
                    >
                    > _watcher = new FileSystemWatch er();
                    >
                    > _watcher.Create d += new FileSystemEvent Handler(OnFileC reated);
                    >
                    > _watcher.Delete d += new FileSystemEvent Handler(OnFileD eleted);
                    >
                    > _watcher.Rename d += new RenamedEventHan dler(OnFileRena med); // NOTE: THIS
                    > MAY NOT BE WORKING.
                    >
                    > SetWatcherPrope rties(_watcher) ;
                    >
                    > // Setup second watcher to watch changed because
                    >
                    > // Create, Delete, and rename don't seem to fire when NotifyFilter is set.
                    >
                    > // NOTE: THIS MAY NOT BE WORKING.
                    >
                    > _watcherChanged = new FileSystemWatch er();
                    >
                    > _watcherChanged .Changed += new FileSystemEvent Handler(OnFileC hanged);
                    >
                    > _watcherChanged .NotifyFilter = NotifyFilters.F ileName |
                    > NotifyFilters.D irectoryName;
                    >
                    > SetWatcherPrope rties(_watcherC hanged);
                    >
                    > }
                    >
                    > # endregion
                    >
                    > # region ***** PUBLIC METHODS *****
                    >
                    > /// <summary>
                    >
                    > /// Release handles to directory. A directory cannot be fully
                    >
                    > /// deleted until it is released. Need to use Dispose because
                    >
                    > /// can't wait for garbage collector.
                    >
                    > /// </summary>
                    >
                    > public void Dispose() {
                    >
                    > _watcher.Dispos e();
                    >
                    > _watcherChanged .Dispose();
                    >
                    > }
                    >
                    > # endregion
                    >
                    > # region ***** PRIVATE METHODS *****
                    >
                    > private void SetWatcherPrope rties(FileSyste mWatcher watcher) {
                    >
                    > watcher.Path = _watchPath;
                    >
                    > watcher.Filter = "*.*";
                    >
                    > watcher.Include Subdirectories = true;
                    >
                    > watcher.EnableR aisingEvents = true;
                    >
                    > }
                    >
                    > private void OnFileCreated(o bject sender, FileSystemEvent Args e) {
                    >
                    > Debug.WriteLine ("FileSystmeMon itor.OnFileCrea ted: " + e.FullPath);
                    >
                    > CallChanged(sen der, e);
                    >
                    > }
                    >
                    > private void OnFileDeleted(o bject sender, FileSystemEvent Args e) {
                    >
                    > Debug.WriteLine ("FileSystmeMon itor.OnFileDele ted: " + e.FullPath);
                    >
                    > CallChanged(sen der, e);
                    >
                    > }
                    >
                    > private void OnFileRenamed(o bject sender, RenamedEventArg s e) {
                    >
                    > Debug.WriteLine ("FileSystmeMon itor.OnFileRena med: " + e.FullPath);
                    >
                    > CallChanged(sen der, e);
                    >
                    > }
                    >
                    > private void OnFileChanged(o bject sender, FileSystemEvent Args e) {
                    >
                    > Debug.WriteLine ("FileSystmeMon itor.OnFileChan ged: " + e.FullPath);
                    >
                    > CallChanged(sen der, e);
                    >
                    > }
                    >
                    > private void CallChanged(obj ect sender, FileSystemEvent Args e) {
                    >
                    >
                    > // Check if should ignore change.
                    >
                    > int currentTime = System.Environm ent.TickCount;
                    >
                    > if (currentTime - _lastChangeTime > _ignoreChangesP eriod) {
                    >
                    > if (this.Changed != null) {
                    >
                    > this.Changed(se nder, e);
                    >
                    > }
                    >
                    > } else {
                    >
                    > Debug.WriteLine ("CallChange d Ignored");
                    >
                    > }
                    >
                    > _lastChangeTime = currentTime;
                    >
                    > }
                    >
                    > # endregion
                    >
                    > #region ***** PROPERTIES *****
                    >
                    > public int IgnoreChangesMi liseconds {
                    >
                    > get { return _ignoreChangesP eriod; }
                    >
                    > set { _ignoreChangesP eriod = value; }
                    >
                    > }
                    >
                    > #endregion
                    >
                    > }
                    >
                    >
                    >
                    > -----
                    >
                    > These methods were in another class that was using The FileSystemMonit or.
                    >
                    > public void StartFileMonito r() {
                    >
                    >
                    > Debug.WriteLine ("Start File Monitor: " + this.Directory) ;
                    >
                    > // Setup file system monitor. This object will alert
                    >
                    > // this image to reload when changes occur to the file system.
                    >
                    > if (_fileSystemMon itor == null) {
                    >
                    > _fileSystemMoni tor = new FileSystemMonit or(_dirPath);
                    >
                    > _fileSystemMoni tor.IgnoreChang esMiliseconds =
                    > AppManager.FILE _SYSTEM_IGNORE_ CHANGES_TIME;
                    >
                    > }
                    >
                    > if (_fileSystemCha ngedHandler == null) {
                    >
                    > _fileSystemChan gedHandler = new
                    > FileSystemMonit or.FileSystemCh angedHandler(Fi leSystemMonitor _OnFileSystemCh anged);
                    >
                    > Debug.WriteLine ("FileSystemHan dler Created: " + this.Directory) ;
                    >
                    > }
                    >
                    >
                    > _fileSystemMoni tor.Changed += _fileSystemChan gedHandler;
                    >
                    > Debug.WriteLine ("FileSystemHan dler Added: " + this.Directory) ;
                    >
                    > }
                    >
                    > public void StopFileMonitor () {
                    >
                    > Debug.WriteLine ("Stoping File Monitor: " + this.Directory) ;
                    >
                    > // Remove event handler;
                    >
                    > if (_fileSystemCha ngedHandler != null) {
                    >
                    > _fileSystemMoni tor.Changed -= _fileSystemChan gedHandler;
                    >
                    > Debug.WriteLine ("FileSystemCha ngedHandler Removed: " + this.Directory) ;
                    >
                    >
                    > }
                    >
                    > if (_fileSystemMon itor != null) {
                    >
                    > _fileSystemMoni tor.Dispose();
                    >
                    > Debug.WriteLine ("FileSystemMon itor Disposed");
                    >
                    > //_fileSystemMoni tor = null;
                    >
                    > }
                    >
                    > }
                    >
                    >
                    >
                    > Hope that helps.
                    >
                    >
                    >
                    >
                    > --
                    > Tom Krueger
                    >
                    > Smart Client DevCenter - http://msdn.microsoft.com/smartclient/
                    > Mobile DevCenter - http://msdn.microsoft.com/mobility
                    >
                    > This posting is provided "as is" with no warranties and confers no rights.
                    >
                    > "Paul" <private@mail.c om> wrote in message
                    > news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=green]
                    >> Hi,
                    >> VB.NET is saying the file I am creating is in use by another process and
                    >> won't complete its task of moving the file to the specified destination
                    >> folder.
                    >> Here is my code (the main bit anyway)....
                    >>
                    >>
                    >> Private Sub LogChange(ByVal source As Object, ByVal e As
                    >> System.IO.FileS ystemEventArgs)
                    >> If e.ChangeType = WatcherChangeTy pes.Created Then
                    >> System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
                    >> End If
                    >>
                    >>
                    >> e.FullPath returns the full path and filename of the file created e.g
                    >> c:\filename.txt
                    >> textboxDest is where the file is to be moved to e.g D:\
                    >> e.Name is the filename without the path e.g. filename.txt
                    >>
                    >> This is the error text...
                    >>
                    >> System.IO.IOExc eption: The process cannot access the file
                    >> "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
                    >> What happens is files get downloaded to the D:\Unsorted\ folder which is
                    >> being monitored by the FileSystemWatch er. The app then tries to move the
                    >> downloaded/created file to the D:\Unsorted\200 5\ folder then the error
                    >> occurs.
                    >>
                    >> Any help much appreciated,
                    >> Thanks
                    >> Paul
                    >>[/color]
                    >
                    >[/color]


                    Comment

                    • petterl

                      #11
                      Re: &quot;Proces s cannot access file&quot; problem

                      I have tried to make something out of the C code into VB.Net code but now
                      even when the isopen routine says that the file is ready to be copied, i
                      thet the same message that the file is in use by other process.

                      here is copy of the routine w/ IsFileOpen

                      Private Sub ProcessFile(ByV al file_name As String, ByVal shName As String)

                      Dim wfile As File



                      fslog.lstFiles. Items.Add(Now.T oString() & " Processed " & file_name)

                      If shName = "Thumbs.db" Then ' = LCase(file_name ) Then

                      Exit Sub

                      End If

                      fslog.lstFiles. Items.Add("file exist " & wfile.Exists(fi le_name))

                      fslog.lstFiles. Items.Add("Is file in use " & isFileOpen(file _name))



                      Do

                      System.Threadin g.Thread.Sleep( 500)

                      Loop While wfile.Exists(fi le_name) And isFileOpen(file _name)



                      wfile.Copy(file _name, ToPath & shName)



                      MessageBox.Show (shName & " har blitt kopiert inn på " & LookPath,
                      "Watcher message", MessageBoxButto ns.OK)

                      fslog.lstFiles. Items.Add(Now.T oString() & " " & shName & " har blitt
                      kopiert inn på " & LookPath)



                      wfile = Nothing

                      End Sub





                      Private Function isFileOpen(ByVa l filename As String) As Boolean

                      Dim sf As System.IO.FileS tream

                      Try

                      sf = System.IO.File. Open(filename, FileMode.Open)

                      Return False

                      Catch ex As System.IO.IOExc eption

                      Return True

                      ex = Nothing

                      Finally

                      If Not IsNothing(sf) Then

                      sf = Nothing

                      End If



                      End Try

                      End Function



                      "Paul" <private@mail.c om> wrote in message
                      news:41e38d2d$0 $87823$65c69314 @mercury.nildra m.net...[color=blue]
                      >I appreciate the code guys and the time spent replying but I'm afraid I
                      >don't have a clue on how introduce any of it into my project as the two
                      >examples posted have been in C as opposed to VB. I just realised I posted
                      >this in the the dotnet.general NG aswell as the donet.languages .vb NG which
                      >I suppose is why I got replies in C!
                      > Sorry for the mistake. I guess I'll keep on looking!
                      >
                      > Cheers,
                      > Paul
                      >
                      >
                      >
                      > "Tom Krueger [MSFT]" <a-tkrueg@online.m icrosoft.com> wrote in message
                      > news:uVfLPZN9EH A.4028@TK2MSFTN GP15.phx.gbl...[color=green]
                      >> Hello,
                      >>
                      >> I'm not sure if you are running into the same issue I had a while back or
                      >> not, but just incase here are my thoughts.
                      >>
                      >> I remember I would get the same error and the only way I could get around
                      >> it was by calling dispose on the FileSystemWatch er. Here are my notes
                      >> from the code I wrote a while back
                      >> /// Release handles to directory. A directory cannot be fully
                      >> /// deleted until it is released. Need to use Dispose because
                      >> /// can't wait for garbage collector.
                      >>
                      >> It worked for me. So I my architectured was a class called
                      >> FileSystemMonit er (which I created) and in this class I setup the
                      >> FileSystemWatch er and exposed the events of FileSystemWatch er. Mine
                      >> might be a bit different in that for each FileSystemWatch er event I had
                      >> them raise a my own Changed event so that my subscribers only had to
                      >> listen to one event when any changes occured.
                      >>
                      >> Then when I needed to start and stop watching I released the references
                      >> to the changed event and called dispose on the FileSystemMonit or. Here
                      >> is some of the code.
                      >>
                      >>
                      >> /// <summary>
                      >>
                      >> /// Monitors the file system for any changes in the specified path.
                      >>
                      >> /// </summary>
                      >>
                      >> public class FileSystemMonit or : IDisposable {
                      >>
                      >>
                      >> # region ***** FIELDS *****
                      >>
                      >> private int _ignoreChangesP eriod;
                      >>
                      >> private int _lastChangeTime ;
                      >>
                      >> private FileSystemWatch er _watcher;
                      >>
                      >> private FileSystemWatch er _watcherChanged ;
                      >>
                      >> private string _watchPath;
                      >>
                      >> public delegate void FileSystemChang edHandler(objec t sender,
                      >> FileSystemEvent Args e);
                      >>
                      >> public event FileSystemChang edHandler Changed;
                      >>
                      >> # endregion
                      >>
                      >> # region ***** CONSTRUCTORS *****
                      >>
                      >> public FileSystemMonit or(string path) {
                      >>
                      >> _watchPath = path;
                      >>
                      >> _watcher = new FileSystemWatch er();
                      >>
                      >> _watcher.Create d += new FileSystemEvent Handler(OnFileC reated);
                      >>
                      >> _watcher.Delete d += new FileSystemEvent Handler(OnFileD eleted);
                      >>
                      >> _watcher.Rename d += new RenamedEventHan dler(OnFileRena med); // NOTE: THIS
                      >> MAY NOT BE WORKING.
                      >>
                      >> SetWatcherPrope rties(_watcher) ;
                      >>
                      >> // Setup second watcher to watch changed because
                      >>
                      >> // Create, Delete, and rename don't seem to fire when NotifyFilter is
                      >> set.
                      >>
                      >> // NOTE: THIS MAY NOT BE WORKING.
                      >>
                      >> _watcherChanged = new FileSystemWatch er();
                      >>
                      >> _watcherChanged .Changed += new FileSystemEvent Handler(OnFileC hanged);
                      >>
                      >> _watcherChanged .NotifyFilter = NotifyFilters.F ileName |
                      >> NotifyFilters.D irectoryName;
                      >>
                      >> SetWatcherPrope rties(_watcherC hanged);
                      >>
                      >> }
                      >>
                      >> # endregion
                      >>
                      >> # region ***** PUBLIC METHODS *****
                      >>
                      >> /// <summary>
                      >>
                      >> /// Release handles to directory. A directory cannot be fully
                      >>
                      >> /// deleted until it is released. Need to use Dispose because
                      >>
                      >> /// can't wait for garbage collector.
                      >>
                      >> /// </summary>
                      >>
                      >> public void Dispose() {
                      >>
                      >> _watcher.Dispos e();
                      >>
                      >> _watcherChanged .Dispose();
                      >>
                      >> }
                      >>
                      >> # endregion
                      >>
                      >> # region ***** PRIVATE METHODS *****
                      >>
                      >> private void SetWatcherPrope rties(FileSyste mWatcher watcher) {
                      >>
                      >> watcher.Path = _watchPath;
                      >>
                      >> watcher.Filter = "*.*";
                      >>
                      >> watcher.Include Subdirectories = true;
                      >>
                      >> watcher.EnableR aisingEvents = true;
                      >>
                      >> }
                      >>
                      >> private void OnFileCreated(o bject sender, FileSystemEvent Args e) {
                      >>
                      >> Debug.WriteLine ("FileSystmeMon itor.OnFileCrea ted: " + e.FullPath);
                      >>
                      >> CallChanged(sen der, e);
                      >>
                      >> }
                      >>
                      >> private void OnFileDeleted(o bject sender, FileSystemEvent Args e) {
                      >>
                      >> Debug.WriteLine ("FileSystmeMon itor.OnFileDele ted: " + e.FullPath);
                      >>
                      >> CallChanged(sen der, e);
                      >>
                      >> }
                      >>
                      >> private void OnFileRenamed(o bject sender, RenamedEventArg s e) {
                      >>
                      >> Debug.WriteLine ("FileSystmeMon itor.OnFileRena med: " + e.FullPath);
                      >>
                      >> CallChanged(sen der, e);
                      >>
                      >> }
                      >>
                      >> private void OnFileChanged(o bject sender, FileSystemEvent Args e) {
                      >>
                      >> Debug.WriteLine ("FileSystmeMon itor.OnFileChan ged: " + e.FullPath);
                      >>
                      >> CallChanged(sen der, e);
                      >>
                      >> }
                      >>
                      >> private void CallChanged(obj ect sender, FileSystemEvent Args e) {
                      >>
                      >>
                      >> // Check if should ignore change.
                      >>
                      >> int currentTime = System.Environm ent.TickCount;
                      >>
                      >> if (currentTime - _lastChangeTime > _ignoreChangesP eriod) {
                      >>
                      >> if (this.Changed != null) {
                      >>
                      >> this.Changed(se nder, e);
                      >>
                      >> }
                      >>
                      >> } else {
                      >>
                      >> Debug.WriteLine ("CallChange d Ignored");
                      >>
                      >> }
                      >>
                      >> _lastChangeTime = currentTime;
                      >>
                      >> }
                      >>
                      >> # endregion
                      >>
                      >> #region ***** PROPERTIES *****
                      >>
                      >> public int IgnoreChangesMi liseconds {
                      >>
                      >> get { return _ignoreChangesP eriod; }
                      >>
                      >> set { _ignoreChangesP eriod = value; }
                      >>
                      >> }
                      >>
                      >> #endregion
                      >>
                      >> }
                      >>
                      >>
                      >>
                      >> -----
                      >>
                      >> These methods were in another class that was using The FileSystemMonit or.
                      >>
                      >> public void StartFileMonito r() {
                      >>
                      >>
                      >> Debug.WriteLine ("Start File Monitor: " + this.Directory) ;
                      >>
                      >> // Setup file system monitor. This object will alert
                      >>
                      >> // this image to reload when changes occur to the file system.
                      >>
                      >> if (_fileSystemMon itor == null) {
                      >>
                      >> _fileSystemMoni tor = new FileSystemMonit or(_dirPath);
                      >>
                      >> _fileSystemMoni tor.IgnoreChang esMiliseconds =
                      >> AppManager.FILE _SYSTEM_IGNORE_ CHANGES_TIME;
                      >>
                      >> }
                      >>
                      >> if (_fileSystemCha ngedHandler == null) {
                      >>
                      >> _fileSystemChan gedHandler = new
                      >> FileSystemMonit or.FileSystemCh angedHandler(Fi leSystemMonitor _OnFileSystemCh anged);
                      >>
                      >> Debug.WriteLine ("FileSystemHan dler Created: " + this.Directory) ;
                      >>
                      >> }
                      >>
                      >>
                      >> _fileSystemMoni tor.Changed += _fileSystemChan gedHandler;
                      >>
                      >> Debug.WriteLine ("FileSystemHan dler Added: " + this.Directory) ;
                      >>
                      >> }
                      >>
                      >> public void StopFileMonitor () {
                      >>
                      >> Debug.WriteLine ("Stoping File Monitor: " + this.Directory) ;
                      >>
                      >> // Remove event handler;
                      >>
                      >> if (_fileSystemCha ngedHandler != null) {
                      >>
                      >> _fileSystemMoni tor.Changed -= _fileSystemChan gedHandler;
                      >>
                      >> Debug.WriteLine ("FileSystemCha ngedHandler Removed: " + this.Directory) ;
                      >>
                      >>
                      >> }
                      >>
                      >> if (_fileSystemMon itor != null) {
                      >>
                      >> _fileSystemMoni tor.Dispose();
                      >>
                      >> Debug.WriteLine ("FileSystemMon itor Disposed");
                      >>
                      >> //_fileSystemMoni tor = null;
                      >>
                      >> }
                      >>
                      >> }
                      >>
                      >>
                      >>
                      >> Hope that helps.
                      >>
                      >>
                      >>
                      >>
                      >> --
                      >> Tom Krueger
                      >>
                      >> Smart Client DevCenter - http://msdn.microsoft.com/smartclient/
                      >> Mobile DevCenter - http://msdn.microsoft.com/mobility
                      >>
                      >> This posting is provided "as is" with no warranties and confers no
                      >> rights.
                      >>
                      >> "Paul" <private@mail.c om> wrote in message
                      >> news:41de0a17$0 $87837$65c69314 @mercury.nildra m.net...[color=darkred]
                      >>> Hi,
                      >>> VB.NET is saying the file I am creating is in use by another process and
                      >>> won't complete its task of moving the file to the specified destination
                      >>> folder.
                      >>> Here is my code (the main bit anyway)....
                      >>>
                      >>>
                      >>> Private Sub LogChange(ByVal source As Object, ByVal e As
                      >>> System.IO.FileS ystemEventArgs)
                      >>> If e.ChangeType = WatcherChangeTy pes.Created Then
                      >>> System.IO.File. Move(e.FullPath , textBoxDest.Tex t & "\" & e.Name)
                      >>> End If
                      >>>
                      >>>
                      >>> e.FullPath returns the full path and filename of the file created e.g
                      >>> c:\filename.txt
                      >>> textboxDest is where the file is to be moved to e.g D:\
                      >>> e.Name is the filename without the path e.g. filename.txt
                      >>>
                      >>> This is the error text...
                      >>>
                      >>> System.IO.IOExc eption: The process cannot access the file
                      >>> "D:\Unsorted\20 05\New.mp3" because it is being used by another process.
                      >>> What happens is files get downloaded to the D:\Unsorted\ folder which is
                      >>> being monitored by the FileSystemWatch er. The app then tries to move
                      >>> the downloaded/created file to the D:\Unsorted\200 5\ folder then the
                      >>> error occurs.
                      >>>
                      >>> Any help much appreciated,
                      >>> Thanks
                      >>> Paul
                      >>>[/color]
                      >>
                      >>[/color]
                      >
                      >[/color]


                      Comment

                      Working...