0

I upload a csv file to AppData folder in project solution and read the content with the code below:

using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
{
    var buffer = new byte[fileUpload.InputStream.Length];
    fileUpload.InputStream.Read(buffer, 0, buffer.Length);
    fs.Write(buffer, 0, buffer.Length);

    var reader = new StreamReader(System.IO.File.OpenRead(fs.Name));// I check path and file itself in AppData folder. its ok
    List<string> listA = new List<string>();
    List<string> listB = new List<string>();
    while (!reader.EndOfStream)
    {            
        var line = reader.ReadLine();
        var values = line.Split(';');
    }

But it throws IOException with message:

The process cannot access the file 'c:\path\App_Data\o_1amtdiagc18991ndq1c1k1c2v1bama.csv' because it is being used by another process.

I couldnt get it how and why it's being used I created this file from original uploaded file with unique name..

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96
  • I think you need to open the file without locking it, see this answer here http://stackoverflow.com/a/3448307/1370442 – Luke Baughan Jul 05 '16 at 11:47

1 Answers1

2

I couldnt get it how and why its being used

Because you've not closed the stream that's writing to it:

using (var fs = new FileStream(Path.Combine(uploadPath, name), ...)

I would suggest you write the file, close the using statement so the handle can be released, then read it:

string fullName = Path.Combine(uploadPath, name);
using (var fs = ...)
{
    // Code as before, but ideally taking note of the return value
    // of Stream.Read, that you're currently ignoring. Consider
    // using Stream.CopyTo
}
// Now the file will be closed
using (var reader = File.OpenText(fullName))
{
    // Read here
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is it really required to close the file and open it again? I don't remember the exact option, but there is one that allows you to read and write to the file – Camilo Terevinto Jul 05 '16 at 11:55
  • @cFrozenDeath: Yes, that's *possible* (using different file sharing modes, or just rewinding the stream) but I think it makes a lot more sense to separate the writing from the reading. – Jon Skeet Jul 05 '16 at 11:59