My lead programmer wants me to use the code below to write out the records on a file.
The problem is that if the file is already existing them it does not delete the old file and create a new file and only appends.
I was doing it another way and he did not like it because it was like VB.
Is there way to check for an existing file and delete it with this "using" statement. I know this seem dumb, but that is what he wants.
public static void Printweekly(string Output)
{
using (StreamWriter weekly = new StreamWriter(Program.location + "\\" + Program.name + Program.weeklyEndDate + ".csv", true))
{
weekly.WriteLine("{0}", Output);
}
}
Can anyone help? Thanks ahead of time.
arep
Loading
Zoran HorvatPosted Jul 5, 2011, 5:22 PM
Zoran
VulpesPosted Jul 6, 2011, 5:41 PM
Sam HobbsPosted Jul 6, 2011, 4:46 PM
The C# language and .Net are designed to use garbage collection. The initial design of C# did not have the IDispose interface; it was added during beta testing of C#. So initially there was no need to ensure that an object is disposed of. The "using" statement was created to ensure that IDispose is called and to ensure that any other relevant cleanup is done. The "using" statement seems inelegant to me and it is a kluge; I agree that it is part of C# that is not designed as well as it could be. There are many other things about C# that are designed well.
A RepaskyPosted Jul 6, 2011, 12:14 PM
Thanks, it does work the way I want it now. I already knew that it will open and close it everytime in the loop. I was opening it with a FileStream as below, but the Lead Programmer did not want it. He wants me to use the new feature of .NET the using statement. In fact, he was over my shoulder telling me what to do. So I thank you for your help. In testing the programs, it was getting irratible to have to go in and delete the file or files everytime. I am going to end up with a lot of programs that do the same thing. So thanks for the help.
arep
A RepaskyPosted Jul 5, 2011, 5:19 PM
Thanks,
arep
Zoran HorvatPosted Jul 5, 2011, 5:13 PM
public static void Printweekly(string Output, bool append)
{
In this way, first call to the method would be made with append=false, and all further calls would be made with append=true.using (StreamWriter weekly = new StreamWriter(Program.location + "\\" + Program.name + Program.weeklyEndDate + ".csv", append))
{
weekly.WriteLine("{0}", Output);
}
}
Zoran
A RepaskyPosted Jul 5, 2011, 5:09 PM
arep
Zoran HorvatPosted Jul 5, 2011, 4:56 PM
That will force StreamWriter to overwrite the file if it exists, or otherwise to create new file if one does not exist.