The process cannot access the file "C:\...." because it is being used by another process. How can i kill the process after i have finished with the file?

Hi

In this app, im uploading a file, then reading the file using StreamReader, then i wish to delete the file afterwards (as another file with the same name might be uploaded again).
This is the method that reads the file uploaded:

        Dim sr As StreamReader = New StreamReader(fname)
        Dim lines As Integer = linecount(fname)
        Dim x As Integer = 0
         Try
            Do While x <= lines
                Dim array As String = sr.ReadLine
                splitArrayAndAddToDB(array)
            Loop
            sr = Nothing
            sr.Close()

right after that i wish to delete the file but when i do, it says that the file is being used by another process. How can i kill the process so that i can access that file again? i tried closing streamreader using sr.Close(), but that did nothing.

Thanks in advance
mnsrAsked:
Who is Participating?
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.

jk_vrCommented:
Hello,

First close the stream reader before making it null.

            sr.Close()
            sr = Nothing

mnsrAuthor Commented:
ye i've tried that but it didnt work

it just doesnt kill the process after it's read the file and put it into an array
jk_vrCommented:
Try to put these in the finally block..
Also
 Try
            Do While x <= lines
                Dim array As String = sr.ReadLine
                splitArrayAndAddToDB(array)
            Loop
Catch
       '
Finally
     if not isnothing(sr) then
      sr.Close()
     end if
      sr = Nothing
End try

also it seems you are not modifying the variable 'x'. Please check this also.

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
mnsrAuthor Commented:
awesome!

it works.. thanks
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
ASP.NET

From novice to tech pro — start learning today.