답변을 찾기 위해 바쁜 동안이 코드를 발견했습니다!사용자가 입력 한 경로가 유효한지 어떻게 확인할 수 있습니까?
string fullPath = @"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);
답변을 찾기 위해 바쁜 동안이 코드를 발견했습니다!사용자가 입력 한 경로가 유효한지 어떻게 확인할 수 있습니까?
string fullPath = @"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);
당신은 File.Exists 방법을 사용할 수 있습니다.
당신은 here을 설명하는 File.Exists
방법을 사용할 수 있습니다
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;
}
}
쉬운 방법은 없습니다.
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
}
}
유효하다고 생각하는 항목은 무엇입니까? – keyboardP
파일의 경우 File.Exists(), 디렉토리의 경우 Directory.Exists() –
http://stackoverflow.com/questions/6198392/check-whether-a-path-is-valid –