使用File.Delete删除文件,然后使用Streamwriter创建相同的文件?

时间:2009-08-18 03:03:07

标签: c# file streamwriter

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)
    {       
    }            
}

我的方法是否会正确删除文件,然后创建一个名为“realmlist.wtf”的文件,然后给它写一行?

我有点困惑,因为我看不到它实际上再次创建文件的行。或者创建StreamWriter的行为是否自动创建文件?

3 个答案:

答案 0 :(得分:3)

如果文件不存在,Stream Writer将创建该文件。 它将在构造函数中创建它,因此在实例化StreamWriter时。

答案 1 :(得分:1)

您知道,如果将FileStream实例传递给StreamWriter构造函数,则可以将其设置为简单地覆盖该文件。只需将它与构造函数一起传递。

http://msdn.microsoft.com/en-us/library/system.io.filestream.filestream.aspx

示例:

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);
}

此外,您无需使用.Close方法。 using()函数可以帮助您。

答案 2 :(得分:0)

尝试System.IO.File.CreateText