473,737 Members | 1,836 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"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
Nov 22 '05 #1
9 3256
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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

Nov 22 '05 #2
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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

Nov 22 '05 #3
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" <pe**********@h otmail.com> wrote in message
news:u2******** ******@TK2MSFTN GP12.phx.gbl...
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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


Nov 22 '05 #4
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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

Nov 22 '05 #5
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" <pr*****@mail.c om> wrote in message
news:41******** *************@m ercury.nildram. net...
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" <pe**********@h otmail.com> wrote in message
news:u2******** ******@TK2MSFTN GP12.phx.gbl...
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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



Nov 22 '05 #6
Petter L wrote:
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


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();
}
}
[...]
Nov 22 '05 #7
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-******@online.m icrosoft.com> wrote in message
news:uV******** ******@TK2MSFTN GP15.phx.gbl...
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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


Nov 22 '05 #8
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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-******@online.m icrosoft.com> wrote in message
news:uV******** ******@TK2MSFTN GP15.phx.gbl...
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" <pr*****@mail.c om> wrote in message
news:41******** *************** @mercury.nildra m.net...
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



Nov 22 '05 #9
petterl wrote:
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.


Hey Petter..

Try using this call in your "isFileOpen " function:

s = System.IO.File. Open(fileName, System.IO.FileM ode.Open,
System.IO.FileA ccess.ReadWrite , System.IO.FileS hare.None);

This will gain exclusive access to the file!

/B.waiting
Nov 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
715
by: Paul | last post by:
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.FileSystemEventArgs) If e.ChangeType = WatcherChangeTypes.Created Then
2
2847
by: Henrik | last post by:
Hi Im trying to make an app that uses threading, I want to write to a file in a loop. How can i ensure that only one thread writes to the file a the time??? Im accessing the fil with: Dim xFile As StreamWriter
4
13247
by: Earth Worm Jim | last post by:
I am using VS.Net 2003 on Windows 2003 Server (standard edition) and I am getting "The process cannot access the file because it is being used by another process" on DLL's in a VS.Net solution. I have made sure all the dependancies and the build order is correct but the actually instance of VS.Net (devenv.exe) is LOCKING THE DAM DLL'S IT IS TRYING TO BUILD. ????? I have used Process Explorer from sysinternals.com to confirm this.
2
3525
by: FrzzMan | last post by:
The first time I called this function, everything went well, but the second time I called it. An Exception thrown, do you know why? An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll Additional information: The process cannot access the file "E:\......\bin\Debug\test.xml" because it is being used by another process. ----------------------------------------------
2
2911
by: lucy | last post by:
Hi, I use ADOX to create a Access database programmatically from my asp.net application and save ".mdb" file to a temp folder under my project foler on the web server. After database is created successfuly, I saw two files ".mdb" and ".ldb" in my temp folder. I have no problem to open the database manually. But when I'm tring to use Response.WriteFile() to download database file to end user's local machine, I kept getting the following
7
23186
by: RSH | last post by:
Hi, I have an ASP .Net web page that creates a temp directory on the server then it is using the File.Copy command to move a file to a temp download directory, Then I am doing a response.Redirect to that URL. The problem is that whenever I run the page the script fails on the File.Copy() command everytime with an error of: The process cannot access the file
9
1802
by: mvsguy | last post by:
I'm a Notes admin tasked with fixing an Access problem. I hope someone will be gracious enough to help. The database is getting a 3420, object not defined, and I need to find all the places where the object is referenced. In Notes, I'd just get a synopsis which shows all executable lines of code in the entire database. Does Access have a similar function?
0
8965
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9330
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9255
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9202
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6748
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6050
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2741
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2191
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.