【发布时间】:2017-02-09 17:23:04
【问题描述】:
所以,我试图在特定路径上创建一个文件,但我拥有的代码不允许我创建文件夹。
这是我的代码:
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\。
你知道怎么做吗?
【问题讨论】:
-
Directory.CreateDirectory
-
你遇到了什么错误,设置
OpenOrCreate标志就足够了。 -
检查 Directory.Exists 然后创建文件
-
@BalajiMarimuthu 您甚至不需要这样做,您可以直接在现有目录上调用
Directory.CreateDirectory,它只会重新运行对现有目录的引用,而不是抛出错误并尝试创建一个新的。 -
@ScottChamberlain 感谢您的解释。
标签: c#