Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically create folders if does not exists in C#

Tags:

c#

So, I am trying to create a file at a specific path but the code I have doesn't allows me to create folders.

This is the code I have:

public void LogFiles()
{
    string data = string.Format("LogCarga-{0:yyyy-MM-dd_hh-mm-ss}.txt", DateTime.Now);
    for (int linhas = 0; linhas < dataGridView1.Rows.Count; linhas++)
    {
        if (dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim() != "M")
        {
            var pathWithEnv = @"%USERPROFILE%\AppData\Local\Cargas - Amostras\_logs\";
            var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                using (StreamWriter writer = File.AppendText(filePath + data))
                {
                    string carga = dataGridView1.Rows[linhas].Cells[0].Value.ToString();
                    string referencia = dataGridView1.Rows[linhas].Cells[1].Value.ToString();
                    string quantidade = dataGridView1.Rows[linhas].Cells[2].Value.ToString();
                    string dataemissao = dataGridView1.Rows[linhas].Cells[3].Value.ToString();
                    string linha = dataGridView1.Rows[linhas].Cells[4].Value.ToString();
                    string marca = dataGridView1.Rows[linhas].Cells[5].Value.ToString().Trim();
                    string descricaoweb = dataGridView1.Rows[linhas].Cells[6].Value.ToString().Trim();
                    string codprod = dataGridView1.Rows[linhas].Cells[7].Value.ToString().Trim();
                    string tipoemb = dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim();
                    string nomepc = System.Environment.MachineName;
                    writer.WriteLine(carga + ", " + referencia + ", " + quantidade + ", " + dataemissao + ", " + linha + ", " + marca + ", " + descricaoweb + ", " + codprod + ", "
                            + tipoemb + ", " + nomepc);
                    }  
                }  
            }
        }
    }

This %USERPROFILE%\AppData\Local\ in the universal path and I want to automatically create the \Cargas - Amostras\_logs\.

Do you have any idea how to do it?

like image 643
SangDang Avatar asked Oct 14 '25 12:10

SangDang


1 Answers

The simpelest solution is replace

using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))

with

System.IO.Directory.CreateDirectory(filePath)

That will create the directory if it does not exist or do nothing if it does.

like image 64
Scott Chamberlain Avatar answered Oct 17 '25 03:10

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!