Solved

Error writing to .csv file

Posted on 2012-03-22
5
626 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 250 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

Enroll in June's Course of the Month

June's Course of the Month is now available! Every 10 seconds, a consumer gets hit with ransomware. Refresh your knowledge of ransomware best practices by enrolling in this month's complimentary course for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

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

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Come and listen to Percona CEO Peter Zaitsev discuss what’s new in Percona open source software, including Percona Server for MySQL (https://www.percona.com/software/mysql-database/percona-server) and MongoDB (https://www.percona.com/software/mongo-…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

691 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