views:

633

answers:

3
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?

+2  A: 

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.

Russell
Just to be clear, the second line inside my Try() statement will create the file?
Sergio Tapia
Yep:"StreamWriter TheWriter = new StreamWriter(Properties.Settings.Default.WoWFolderLocation + "Data/realmlist.wtf");"
Russell
All I needed to know, thank you very much!
Sergio Tapia
A: 

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.

WebDevHobo
A: 

Try System.IO.File.CreateText

John JJ Curtis