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