0

我正在尝试将 a 转换DataTable为 excel 文件,但在创建文件时它给了我错误:找不到路径的一部分

string strDirectorypath = HttpContext.Current.Server.MapPath("~/ExcelUpload/");
DateTime dtbatchtime = Convert.ToDateTime(strBatchProcesstime);
strBatchProcesstime = dtbatchtime.ToString("MM-dd-yyyy_hh_mm_ss");

string strFilename = "FailedExcel_" + strBatchProcesstime + ".csv";
string csvdownloadPath = Path.Combine(strDirectorypath, strFilename);
using (FileStream File_Stream = new FileStream(csvdownloadPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
    using (StreamWriter FileWriter = new StreamWriter(File_Stream))
    {
        FileWriter.BaseStream.Seek(0, SeekOrigin.End);
        string[] columns = { "Opportunity Name", "Property Id", "Error Type", "Error Message", "Time" };//set columns here as in the Excel Sheet.
        CreateColumns(FileWriter, columns);
        FileWriter.WriteLine();
        if (dtRecords.Rows.Count > 0)
        {
            for (int i = 0; i < dtRecords.Rows.Count; i++)
            {
                string[] values = { 
                    dtRecords.Rows[i]["OpportunityName"].ToString(), 
                    dtRecords.Rows[i]["PropertyId"].ToString(), 
                    dtRecords.Rows[i]["ErrorType"].ToString(), 
                    dtRecords.Rows[i]["ErrorMessage"].ToString(), 
                    dtRecords.Rows[i]["TimeStamp"].ToString() 
                };
                CreateColumns(FileWriter, values);
                FileWriter.WriteLine();
            }
        }

    }
}
4

1 回答 1

0

如果该目录不存在,则不会创建,因此您应该检查并创建:

if (!Directory.Exists(strDirectorypath)) {
  Directory.Create(strDirectorypath);
}

通过对您自己的可靠性/健全性的检查程度来扩展它。

于 2013-02-22T11:46:11.037 回答