我在忙着寻找答案时找到了这段代码!
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
if (pcapFile != "")
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}
答案 0 :(得分:2)
没有简单的方法。
您可以使用File.Exists
检查路径上是否存在文件,但在执行下一行之前仍可能发生更改。您最好的选择是将File.Exists
与try-catch
结合使用以捕获任何可能的异常。
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
try
{
if (File.Exists(pcapFile))
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}
catch (FileNotFoundException fileNotFoundException)
{
//Log and handle
}
catch (Exception ex)
{
//log and handle
}
}
答案 1 :(得分:1)
您可以使用File.Exists方法:
string fullPath = @"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);
答案 2 :(得分:1)
您可以使用File.Exists
方法,该方法记录在案here。