string.Replace 没有替换我的字符串中的双反斜杠

string.Replace is not replacing double backslashes from my string

我需要 运行 某种应用程序,方法是单击我表单上的一个按钮, 我在谈论 WPF 桌面应用程序,以及 C# 作为一种编程语言,今天我遇到了一个问题,我试图 运行 按下按钮键上的某种应用程序,但我通过调试器意识到我的路径是这样写的:(我在 Settings.setting 文件中保留了路径,但我没有使用双反斜杠,这是我的第一个问题,为什么我的路径看起来像那样, 如下所述.)

C:\\MyComputer\\MyApplication\\Application.exe

我需要用单反斜杠编写它,我尝试做的事情发布在下面:

 private void OpenApplication_Click(object sender, MouseButtonEventArgs e)
 {
            string path = Globals.MyApplicationPath;
            string path2 = path.Replace(@"\", @"\");
            //path2 is still dobule backshashed :(

            if (Directory.Exists(path2))
            {
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = Globals.MyApplicationPath;
                Process.Start(start);
            }
            else
            {
                MessageBox.Show("Path is not correct.");
            }
 }

我意识到Directory.Exists(path2)总是错误的,所以它实际上意味着我的路径不存在,即使它存在,所以我想我需要删除“\\”并用“\”替换它:)

我想我知道问题出在哪里了。

您的路径包含一个文件名。 Directory.Exists() 方法将 return false 因为那不是有效的 目录 名称。

如果你要做的是找到目录,然后去掉文件名然后检查:

var path2 = Path.GetDirectoryName(path);
var exists = Directory.Exists(path2) //This should be true

如果你想知道文件是否存在,使用:

File.Exists(path)

因此您的代码变为:

private void OpenApplication_Click(object sender, MouseButtonEventArgs e)
{
        if (File.Exists(Globals.MyApplicationPath))
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = Globals.MyApplicationPath;
            Process.Start(start);
        }
        else
        {
            MessageBox.Show("Path is not correct.");
        }
}