create a file with content in C # and save to a folder on the computer

2

I need to create a report and save this report to a folder inside the computer's C: drive, I can only save the file without the content and the blank name.

The save code:

string folder = System.Configuration.ConfigurationManager.AppSettings["Relatorios"] + usuario;
string arquivo = folder + @"\" + nomearquivo;

if (!Directory.Exists(folder))
{
    Directory.CreateDirectory(arquivo + ".txt " + relatorio);
}

if (!File.Exists(arquivo))
{
    File.Create(arquivo+".txt " + relatorio);
}               
else
{
    File.Delete(arquivo);
    File.Create(arquivo + ".txt " + relatorio);
}
    
asked by anonymous 11.05.2017 / 14:56

2 answers

6

There are several problems there. I've improved your code overall.

  • Use Path.Combine() instead concatenate the strings with the backslash (this is another tip).

  • You do not need to verify that the directory exists before Directory.CreateDirectory() " because this method only creates the file if it does not exist.

  • You do not need to delete the file to recreate it. The File.Create() method creates a file if it does not exist, if the file with this name already existed, it will be overwritten.

  • Watch out for open streams .

    File.Create() will return a FileStream , this FileStream is not being closed and you need to be careful about it . So I put Dispose() after the Create() .

    Read about this at: What is the use of using? , What kind of features are released in a "using" statement? , Should I always use Dispose?

  • You have not written the contents of the file. The Create() method receives only the file name, you are concatenating what the content should be together with the name.

    In my example, I used WriteAllLines() to write it down. It receives as a parameter IEnumerable<string> and causes each element of this collection to be a line of the file. I used this method because it is much simpler and does not risk leaking resources.

  • The code:

    Assuming that relatorio is a collection of string (array, list, etc.).

    List<string> relatorio = /*Fazer algo para carregar o relatório*/;
    
    string folder = System.Configuration.ConfigurationManager.AppSettings["Relatorios"] + usuario;;
    string arquivo = Path.Combine(folder, "arquivo.txt");
    
    Directory.CreateDirectory(folder);
    
    File.Create(arquivo).Dispose();
    
    File.WriteAllLines(arquivo, relatorio);
    
        
    11.05.2017 / 15:19
    2

    link

     string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path)) 
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }   
        }
    
        
    11.05.2017 / 15:18