Reputation: 41128
public void LoadRealmlist()
{
try
{
File.Delete(Properties.Settings.Default.WoWFolderLocation +
"Data/realmlist.wtf");
StreamWriter TheWriter =
new StreamWriter(Properties.Settings.Default.WoWFolderLocation +
"Data/realmlist.wtf");
TheWriter.WriteLine("this is my test string");
TheWriter.Close();
}
catch (Exception)
{
}
}
Will my method properly delete a file, then create one with "realmlist.wtf" as the name and then write a line to it?
I'm kind of confused because I can't see the line where it actually creates the file again. Or does the act of creating a StreamWriter automatically create a file?
Upvotes: 1
Views: 13909
Reputation: 14529
You know, if you pass a FileStream instance to the StreamWriter constructor, it can be set to simply overwrite the file. Just pass it along with the constructor.
http://msdn.microsoft.com/en-us/library/system.io.filestream.filestream.aspx
Example:
try
{
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
//FileMode.Create will make sure that if the file allready exists,
//it is deleted and a new one create. If not, it is created normally.
using (StreamWriter sw = new StreamWriter(fs))
{
//whatever you wanna do.
}
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
Also, with this you won't need to use the .Close
method. The using()
function does that for you.
Upvotes: 2
Reputation: 17719
The Stream Writer will create the file if it doesn't exist. It will create it in the constructor, so when the StreamWriter is instantiated.
Upvotes: 3