有些时候在程序中我们需要用户自己去选择文件夹的路径或者文件的路径,那这时怎么做呢。
/// <summary>
/// 获取文件路径
/// </summary>
/// <param name="HistoryPath">历史路径,可以在弹出选择路径前选定此路径,当然也可以不用设置</param>
/// <returns></returns>
private string GetFilePath(string HistoryPath)
{
try
{
string FilePath = "";
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "请选择文件";
dialog.Filter = "所有文件(*.*)|*.*";
if (!string.IsNullOrWhiteSpace(HistoryPath)) dialog.FileName = HistoryPath.Trim();
if (dialog.ShowDialog() == DialogResult.OK)
{
FilePath = dialog.FileName;
if (string.IsNullOrWhiteSpace(FilePath))
{
MessageBox.Show(this, "文件路径不能为空", "提示");
return "";
}
else
{
return FilePath;
}
}
return FilePath;
}
catch (Exception e)
{
MessageBox.Show(e.Message + e.InnerException);
return "";
}
}
/// <summary>
/// 获取文件夹路径
/// </summary>
/// <param name="HistoryPath">历史路径,可以在弹出选择路径前选定此路径,当然也可以不用设置</param>
/// <returns></returns>
private string GetFolderPath(string HistoryPath)
{
try
{
string FolderPath = "";
FolderBrowserDialog Dialog = new FolderBrowserDialog();
Dialog.Description = "请选择文件路径";
if (!string.IsNullOrWhiteSpace(HistoryPath)) Dialog.SelectedPath = HistoryPath;
//Dialog.RootFolder = Environment.SpecialFolder.Programs;
if (Dialog.ShowDialog() == DialogResult.OK)
{
FolderPath = Dialog.SelectedPath;
if (string.IsNullOrWhiteSpace(FolderPath))
{
MessageBox.Show(this, "文件夹路径不能为空", "提示");
return "";
}
else
{
return FolderPath;
}
}
return FolderPath;
}
catch (Exception e)
{
MessageBox.Show(e.Message + e.InnerException);
return "";
}
}