Supprimer le fichier en utilisant File.Delete, puis en utilisant un StreamWriter pour créer le même fichier?

StackOverflow https://stackoverflow.com/questions/1291577

  •  18-09-2019
  •  | 
  •  

Question

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

Est-ce que ma méthode supprimer correctement un fichier, puis créer un avec « realmlist.wtf » comme le nom, puis écrire une ligne à elle?

Je suis un peu confus parce que je ne vois pas la ligne où il fait crée à nouveau le fichier. Ou le fait de créer un StreamWriter créer automatiquement un fichier?

Était-ce utile?

La solution

Le Writer Stream crée le fichier si elle n'existe pas. Il va créer dans le constructeur, alors quand le StreamWriter est instancié.

Autres conseils

Vous savez, si vous passez une instance FileStream au constructeur StreamWriter, il peut être configuré pour écraser simplement le fichier. Il suffit de le transmettre avec le constructeur.

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

Exemple:

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

En outre, avec cela, vous aurez pas besoin d'utiliser la méthode .Close. La fonction using() fait pour vous.

Essayez System.IO.File.CreateText.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top