Share via


StreamWriter wirtes an empty file

Question

Monday, June 4, 2007 11:54 AM

Hello All,

 I have a problem with a StreamWriter. Hoping that somebody can help. After I use it to export my log table to a csv file, the CSV file is empty. I know the table is not empty because I bind it on the page to a GridView and it has data in it. Here is a code snippet of the function which writes the DATATABLE to a CSV log file:

 protected void OnExportLogTableToCSV(DataTable dt)
    {
        StreamWriter sw = null;
        FileStream fs = null;
        try
        {
            string path = @"c:\junk\;

            string logFile = "MyLogFile.csv";

           
            if (File.Exists(path + logFile))
            {
                File.Delete(path + logFile);
            }
            else
            { }
            
            fs = new FileStream(path + logFile,
                FileMode.CreateNew, FileAccess.Write, FileShare.None);

           
           sw = new StreamWriter(logFile, true);
           
            // First we will write the headers.
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
            // Now write all the rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());
                    }
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
            }
        }
        catch (Exception ex)
        {
            ErrorMsg_lbl.Text = "Unable to write to a log file." + "<br /> <strong>Error Details:</strong> " + ex.Message.ToString();
        }
        finally
        {
            if (sw != null)
            {
                sw.Flush();
                sw.Close(); }
            if (fs != null)
            {
                fs.Flush();
                fs.Close();
            }
        }
       
    }

Thank you,

Tatyana 

All replies (5)

Tuesday, June 5, 2007 12:30 PM ✅Answered

Using @"\\\\" would specify 4 slashes, and not two.  You seem to be looking for "\\" or @"\\" .  What you should do is specify the full path in the LogFilesPath value and not a partial path.  This would allow you to put the file literally anywhere you have access without having to mess with the path.

You can use the following code to always create or truncate a file:

new StreamWriter(new FileStream(Path + Filename, FileMode.Create));

To write a new file every time, then you will need to guarantee the filename is unique. You can do that by creating a separate function that loops until it finds a unique name, such as by prepending a number until it finds a number that is not taken.


Tuesday, June 5, 2007 3:28 PM ✅Answered

hi

 

first of all your appending of four slashes is creating problem. as your are using @ before \\ it makes your file path as \\YourNetworkDrive\YourFolder

putting @ above any line will make the rest of thing following it a string literal. And now the second thing is why you are using file stream once your have wrote like this. StreamWriter streamWriter=new StreamWriter("PassYourFilePathHere"); 

and for uniqueness what you can do is first check if (File.Exits("FilePath")) , add datetime stamp in the end of you can add DateTime.Ticks, if file not exits

then just do straight StreamWriter streamWriter=new StreamWriter("PassYourFilePathHere");

 streamWriter.Write("YourContent");

streamWriter.Close();

streamWriter.Dispose();

 it will also create your file.

thanks

vishal 


Monday, June 4, 2007 2:59 PM

Does this file exist whereever this code is in your app structure?  You are giving the streamwriter a file name, but not the path-- you only specified the path in the filestream.  You should have just said sw = New StreamWriter(fs);, since a streamwriter can be created with another stream type.

Also, closing the streamwriter would close the filestream it was created from, therefore you do not have to flush & close your filestream.

 


Tuesday, June 5, 2007 11:56 AM

Thank you very much for the answer! I checked the code and fixed the things you suggeted and it now writes to a c:\junk with no problem. The only thing is I'm getting an error when writing to a network wrive:

string path = @\\ + ConfigurationManager.AppSettings["LogFilesPath"].ToString();

 Where <add key="LogFilesPath" value="MyNetworkDrive\MyFolder\ />

That fails with error: Can not find the file.

But if I use string path = @"c:\junk\; it works fine.

Aslo I had to create a file myself in that directory, it won't create a file, says it doesn't exist. Still nothing. How can I write a new file everytime? Why won't the FileStream create it from scratch? What if I need to create a new log everytime without overriding the previous?

Thank you,

Tatyana


Thursday, June 7, 2007 11:41 AM

Thank you so much for the answers! I will try this now!