VB.NET problem streamreader

hi.
I get an excaption... some times not all the times.

I try to translate the error
Processen can not acess the file C:\a\TO000040.csv because it used by other process..



The long expections is this

System.IO.IOException was unhandled
  Message=Processen kan inte komma åt filen C:\a\TO000040.csv eftersom den används i en annan process.
  Source=mscorlib
  StackTrace:
       vid System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       vid System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
       vid System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
       vid System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
       vid System.IO.StreamReader..ctor(String path)
       vid FrmMain.SaveCsvToDataset() i C:\00 Projekt\Forms\FrmMain.vb:rad 1385
       vid FrmMain.OnChanged(Object source, FileSystemEventArgs e) i C:\00 Projekt\FrmMain.vb:rad 1361
       vid System.IO.FileSystemWatcher.OnCreated(FileSystemEventArgs e)
       vid System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)
       vid System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
       vid System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
  InnerException:


Public watcher As New FileSystemWatcher()

 Public Sub Start_Watch()
        watcher.Path = "c:/a/"   

        ' Watch for changes in LastAccess and LastWrite times, and
        ' the renaming of files or directories. 
        watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)
        ' Only watch text files.
        watcher.Filter = "*.csv"

        AddHandler watcher.Created, AddressOf OnChanged

        ' Begin watching.
        watcher.EnableRaisingEvents = True
    End Sub



 Public Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
        ' Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine("File: " & e.FullPath & " " & e.ChangeType)

       

        SaveCsvToDataset()

    End Sub


 Public Sub SaveCsvToDataset()
 watcher.EnableRaisingEvents = False
  Dim sr As New StreamReader(csvfilepath)   '<- (Hera I get it)

'maybe I get this because I have used it as a watcher before?

Open in new window

kavvisAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Pratima PharandeCommented:
check whether is file is already open , close it and try again
0
CluskittCommented:
That happens to me a lot. One of the things that could be happening is that you open the file, then you have an exception happen which causes the code to stop before you close the file. When that happens, the file is still locked by IIS (or whichever engine you're using) and you can't open it.
Restarting the service usually frees the file. Also, use a try/catch block to always close the file.
0
kavvisAuthor Commented:
pratima_mcs:  the file is not open in any editor , (vb.net reads the file put is done before i read a new file.)
I do I close sr.close()  Is this not correct close?

Cluskitt:
hmm.. have you find some work around.. I can´t do the try catch
I have to figure this out..

It´s like this.. I wait for a new file to be created. When it´s created I read the csv. into a datable. Then I move the file to a nother location and I use the data in the datable.


is the problem that I do   "Dim sr As New StreamReader(csvfilepath)"
 ?
0
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

CluskittCommented:
The only workaround you can do, without using the try/catch, is to create a copy of the file and work on that instead. It's the only way to be sure it won't be locked. At least, that I know of.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kavvisAuthor Commented:
I have tried this to.. but then I get the same problem when I make the copy..

Do you have a better way than I to make a copy... please give me some tips on a way just to coppy the file..
0
kavvisAuthor Commented:
I made a new coppy and then I use try catch so when it happends I just don´t care.. because it will be correkt anyway if I have the expection or not... thank you
0
mcs0506Commented:
Hi,
Use locking mechanism when you io operation

SyncLock someLock

    'All of your file  IO related code with close and dispose function

End SyncLock






Dani
 
0
kavvisAuthor Commented:
mcs0506:

OK. I can´t understand how to use it so please make som more exampel
0
kavvisAuthor Commented:
This I still have problem with the exaption...
can I how someway make a nother copy that not care if the file is in use or not...
I try tills try catch and if I get exaption then I do the copy anyway..


Try
            'Try copy file...
            If System.IO.File.Exists(FileToCopy) = True Then
                System.IO.File.Copy(FileToCopy, NewCopy)

            End If
        Catch
            'If exaption try copy anyway
            If System.IO.File.Exists(FileToCopy) = True Then
                System.IO.File.Copy(FileToCopy, NewCopy)

            End If
0
CluskittCommented:
There is no point in that. If it throws an exception the first time, it will keep on doing that. Your best bet would be to open it as read-only. Though it seems that the file is system-locked (meaning that it's locked even from reading). In that case, you can't solve it from your end, but from the end that creates and handles the file.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.