?
Solved

Error writing to .csv file

Posted on 2012-03-22
5
Medium Priority
?
636 Views
Last Modified: 2012-06-21
Hi  I have some code which goes round in a loop and writes to a .csv file.  This all works perfectly on my laptop (Vista and Visual Web Developer Express).  However, to my horror when I copied the files across to my client's server (running Windows 2008) I got the following error message:

The process cannot access the file 'C:\inetpub\wwwroot\DR\Admin\uploaded\35201203211547.csv' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

I then closed down the browser and attempted to manually delete the file using Windows Explorer but it wouldn't let me delete it and gave me this message:

File in Use
The action can't be completed because the file is open in IIS Worker Process.

No-one else was accessing the website while I was on it so how on earth could the file have been used by another process??  Please someone help as this is very embarassing for me!
0
Comment
Question by:Lorna70
  • 3
5 Comments
 
LVL 17

Expert Comment

by:nepaluz
ID: 37751643
what's the code you are using to read the file? If you are using File.ReadAllLines() then you can change that to a TextFieldParser() or StreamReader() to evercome the error.
0
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 750 total points
ID: 37751791
Looks like your code to Write CSV File is not releasing the file handle.
Here is the proper way to write to a file safely releasing the handle:-

       
// Create  the  bytes to write to the  temporary file.   
       Byte[]  bytesToWrite = new  Byte[]  { 1, 2, 3, 4, 5 };   
  
       // Create  the  temporary file.   
       using (FileStream  fs = new  FileStream("Temp.csv", FileMode.Create)) {  
         // Write the  bytes to the  temporary file.   
         fs.Write(bytesToWrite, 0, bytesToWrite.Length);  
       }  
  
       // Delete  the  temporary file.   
       File.Delete("Temp.dat");

Open in new window


Here inside using statement, the fs object is automatically disposed which finalizes the SafeHandle object inside FileStream. The Safehandle object actually contains native handle to the file you have opened to write.
0
 

Author Comment

by:Lorna70
ID: 37752040
Thanks - this is my (summarised) code - I'm a newbie to writing to files so can someone please tell me how I dispose of the object.  I don't want to delete the file obviously (presumably just the handle to the object as 'BuggyCoder' says) :

int i = 0;
while (i < 10)
              {
                call function to process
                getSubmissionDetails(i);
              }

protected void getSubmissionDetails(int lineNo)
{
        string pathToFile = Server.MapPath(" uploaded/");
        DateTime d = DateTime.Now;
        string dateTimeNow = d.ToString("yyyyMMddHHmm");
        string strFileName = "12" + dateTimeNow + ".csv";
        string fullPath = pathToFile + "\\" + strFileName;

        //add info to .csv file
        StreamWriter objStreamWriter;
        objStreamWriter = File.AppendText(fullPath);

        string buyerNotesLine1 = "START,TEST,Internal Ref " + ID + ",1";
        string buyerNotesLine2 = "XXX," + dateTimeNow + ",New,,";

        objStreamWriter.WriteLine(buyerNotesLine1);
        objStreamWriter.WriteLine(buyerNotesLine2);
        int k = 0;
        while (k < 10)
              {
                    objStreamWriter.WriteLine("22/03/2012 is todays date");
              }
        objStreamWriter.Close();
}
0
 

Author Comment

by:Lorna70
ID: 37769854
Thanks - apparently if you surround the code by 'using' this disposes of the handle without any need to close the FileStream object.
0
 

Author Closing Comment

by:Lorna70
ID: 37769859
I've just selected 'good' because I didn't use the exact code - wasn't sure about the Delete part as I didn't want to delete my file after writing to it (maybe I didn't understand the proposed soution.  Surrounded my code with 'using' though as this gets rid of the handle without having to Close the object.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Loops Section Overview
Suggested Courses
Course of the Month16 days, left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question