【发布时间】:2017-12-19 16:32:17
【问题描述】:
我正在使用FolderBrowserDialog 让用户选择一个位置来保存文件和/或创建一个新文件夹。它在 99% 的时间都在工作,但是在某些情况下,当用户单击“创建新文件夹”按钮,更改名称,然后单击“确定”时,将抛出“新文件夹”不存在的异常。
看起来代码仍在寻找名称为“新文件夹”的文件夹,即使用户对其进行了重命名。我可以在我的代码中进行哪些更改来处理此问题,以便文件始终保存在用户选择的文件夹中?
//Declaring Filename
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
folderDlg.Description = "Choose the location to save Files";
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
savelocation = folderDlg.SelectedPath;
}
// Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
dataGridExport.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
// Select all the cells
dataGridExport.SelectAll();
// Copy selected cells to DataObject
DataObject dataObject = dataGridExport.GetClipboardContent();
// Get the text of the DataObject, and serialize it to a file
File.WriteAllText(savelocation + "\\ExcelExport.csv", dataObject.GetText(TextDataFormat.CommaSeparatedValue));
【问题讨论】:
-
@CaiusJard - 你有替代方法来实现允许用户选择保存位置吗?
-
顺便说一句,始终使用 Path.Combine 创建文件路径。
-
您没有代码来处理对话结果不是
DialogResult.OK的情况,当使用savelocation的默认值时可能会出现问题,因为DialogResult不同? -
@0liveradam8 - 我逐步检查了我的代码,当 DialogResult.OK 和用户创建一个新文件夹时会发生这种情况
标签: c# folderbrowserdialog writealltext