c# - 如果在 C# 中不存在,则自动创建文件夹

标签 c#

因此,我尝试在特定路径创建一个文件,但我的代码不允许我创建文件夹。

这是我的代码:

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

通用路径中的这个 %USERPROFILE%\AppData\Local\ 我想自动创建 \Cargas - Amostras\_logs\

你知道怎么做吗?

最佳答案

最简单的解决方案是替换

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

System.IO.Directory.CreateDirectory(filePath)

如果目录不存在,将创建该目录;如果存在,则不执行任何操作。

关于c# - 如果在 C# 中不存在,则自动创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42143052/

相关文章:

c# - 具有来自其他数据表的 id 的数据表,需要转换此数据表以将 id 替换为其数据表名称列值

c# - 在状态转换中产生最短路径

c# - 在 .NET 项目中移动项目文件

javascript - 解码使用 JS encodeURIComponent 函数编码的参数

c# - 如何显示字节数组的十六进制值?

c# - WPF : Remove control's explicit foreground color

c# - 如何在 Windows 商店应用程序中截取屏幕截图

c# - 将 '.ToString()' 与数值变量一起使用

c# - 跨平台随机数生成器

c# - 如何在我的类(class)中正确实现 Dispose()?