如何修复此DirectoryNotFoundException?

时间:2016-10-13 10:49:44

标签: c# wpf path

我在.txt文件上有一个DirectoryNotFoundException,如果我使用它正在运行的完整路径但是我不想使用完整路径,因为我希望程序无论放在何处都能正常工作(与计算机的最大兼容性) )

这是我的代码

private void SaveClose_Click(object sender, RoutedEventArgs e)
{
    if (Windowed.IsChecked == true)
        windowed = true;
    else
        windowed = false;

    string textWriteWindowed;

    if (windowed == true)
    {
        textWriteWindowed = "-screen-fullscreen 0" + Environment.NewLine;
    }
    else
    {
        textWriteWindowed = "-screen-fullscreen 1" + Environment.NewLine;
    }

    var selectedResolution = ResolutionBox.SelectedItem.ToString();
    var split = selectedResolution.Split('x');
    widthChoose = Int32.Parse(split[0]);
    heightChoose = Int32.Parse(split[1]);

    string textWriteWidth;
    textWriteWidth = "-screen-width " + widthChoose + Environment.NewLine;

    string textWriteHeight;
    textWriteHeight = "-screen-height " + heightChoose + Environment.NewLine;

    File.WriteAllText(@"\Resources\arguments.txt", textWriteWindowed);
    File.AppendAllText(@"\Resources\arguments.txt", textWriteWidth);
    File.AppendAllText(@"\Resources\arguments.txt", textWriteHeight);

    this.Close();
}

4 个答案:

答案 0 :(得分:3)

if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } 的第一个参数将路径作为输入。无论你提到的是什么都不是绝对路径,但它只是文件的相对路径。 File.WriteAllText创建文件但不自行创建目录。如下所示:

WriteAllText

应该工作(并在相应的驱动器中创建文件),但

File.WriteAllText(@"\arguments.txt", textWriteWindowed);

不起作用。因此,如果要在应用程序所在的路径中创建文件,可以执行以下操作:

File.WriteAllText(@"\Resources\arguments.txt", textWriteWindowed);

如果要创建目录,则可以执行以下操作:

string folder=Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
File.WriteAllText(@"\arguments2.txt", "ABC");

希望这可以回答您的问题。

答案 1 :(得分:0)

在保存文件之前,你必须检查文件夹是否存在,

如果文件夹不存在,请使用

创建它
Directory.CreateDirectory(...)

Directory.Exists(..) 

您可以用来检查文件夹是否存在

答案 2 :(得分:0)

我不知道怎么做但这样做对我有用:

  

File.WriteAllText(@"./arguments.txt", textWriteWindowed); File.AppendAllText(@"./arguments.txt", textWriteWidth); File.AppendAllText(@"./arguments.txt", textWriteHeight);

答案 3 :(得分:0)

如果您想获取正在执行的文件的本地路径,请使用以下命令:

 var fInfo = new FileInfo(System.Reflection.Assembly.GetCallingAssembly().Location);

从那里,您将执行以下操作:

var parentDir = new DirectoryInfo(fInfo.DirectoryName);
var subDir = new DirectoryInfo(parentDir.FullName + "Resource");
if(!subDir.Exists)
   subDir.Create();

这将确保您的可执行文件目录中始终有一个文件夹。但正如你所知,这是绝对可怕的代码,永远不应该在类似环境的生产中实现。如果某个指关节sysAdmin决定将您的程序/文件夹放在当前用户无法访问/写入的区域中,该怎么办?写入的最佳位置是%APPDATA%,这将确保用户始终对您要完成的操作具有读/写权限。