Solved

Error writing to .csv file

Posted on 2012-03-22
5
618 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 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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Contant UI messages in .NET 1 41
HTML table 7 54
WPF issue with Trigger 2 69
Problem to page 4 27
This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now