C# 为什么我的代码抛出io.system.directorynotfound?
为什么下面的代码会引发io.system.directorynotfound异常?我自己无法重现这个问题,但我代码的另一个用户确实看到了,你知道为什么吗? 谢谢C# 为什么我的代码抛出io.system.directorynotfound?,c#,directory,C#,Directory,为什么下面的代码会引发io.system.directorynotfound异常?我自己无法重现这个问题,但我代码的另一个用户确实看到了,你知道为什么吗? 谢谢 检查路径是否存在时,您是否尝试过使用System.IO.Directory.Exists而不是System.IO.File.Exists?检查路径是否存在时,您是否尝试过使用System.IO.Directory.Exists而不是System.IO.File.Exists?您正在使用System.IO.File检查目录是否存在而不是S
检查路径是否存在时,您是否尝试过使用System.IO.Directory.Exists而不是System.IO.File.Exists?检查路径是否存在时,您是否尝试过使用System.IO.Directory.Exists而不是System.IO.File.Exists?您正在使用
System.IO.File
检查目录是否存在而不是System.IO.Directory
。它可能在您的机器上工作,因为该目录已经存在,所以检查并不重要
无论哪种方式,您都需要记住,文件系统是不稳定的。不要检查是否存在,而是尝试打开资源并在异常失败时处理异常。您正在使用
System.IO.File
而不是System.IO.directory
检查目录是否存在。它可能在您的机器上工作,因为该目录已经存在,所以检查并不重要
无论哪种方式,您都需要记住,文件系统是不稳定的。不要检查是否存在,而是尝试打开资源并在异常失败时处理异常。检查目录是否存在,而不是文件是否存在
虽然你正在检查它,如果它不存在,你就创建它。你不知道他们是否有创建目录的特权。因此,您的Directory.CreateDirectory调用可能也会失败,然后接下来代码的其余部分将失败检查目录是否存在,而不是文件是否存在 虽然你正在检查它,如果它不存在,你就创建它。你不知道他们是否有创建目录的特权。因此,您的Directory.CreateDirectory调用可能也会失败,然后接下来代码的其余部分也会失败 “评论 Exists方法不应用于路径验证,此方法仅检查路径中指定的文件是否存在。将无效路径传递给Existsl将返回false。“ 这就是你的错误。您的验证无法确保文件的路径存在 “评论 Exists方法不应用于路径验证,此方法仅检查路径中指定的文件是否存在。将无效路径传递给Existsl将返回false。“ 这就是你的错误。您的验证无法确保文件的路径存在
try
{
//create path
string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
//check path exists
if (!System.IO.File.Exists(strAppData))
{
System.IO.Directory.CreateDirectory(strAppData);
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
int count = dir.GetFiles().Length;
if (count > 100)
{
string[] files = System.IO.Directory.GetFiles(strAppData);
foreach (string file in files)
{
System.IO.File.Delete(file);
}
}
this.fileName = fileName;
// delete the file if it exists
if (File.Exists(fileName))
{
//delete the file
File.Delete(fileName);
}
// write the data to the file
fs = File.OpenWrite(fileName);
sWriter = new StreamWriter(fs);
sWriter.WriteLine(headerText);
sWriter.Flush();
sWriter.Close();
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}