string.Replace不替换我的字符串

时间:2017-09-04 16:47:54

标签: c# wpf string replace settings

我需要点击表单上的按钮运行某种应用程序, 我在谈论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)总是假的,所以它实际意味着我的路径不存在,即使它存在,所以我想我需要删除“\\”并将其替换为“\”:)

1 个答案:

答案 0 :(得分:1)

我想我知道问题所在。

您的路径包含文件名。 Directory.Exists()方法将返回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.");
        }
}