StartupPath在c#

时间:2016-04-12 13:30:25

标签: c# winforms filepath

我目前正在尝试重定向路径以将图像保存到文件夹中。

启动路径是:

C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug

我试图改变它,就像它一样:

C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication

我目前使用的代码是:

private void browseBtn_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                //open directory
                open.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|ALL Files (*.*)|*.*";
                open.FilterIndex = 1;
                if(open.ShowDialog() == DialogResult.OK)
                {
                   if(open.CheckFileExists)
                   {
                       string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
                       System.IO.File.Copy(open.FileName, paths + "\\Images\\sss.jpg");
                   }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

有关此事的任何帮助或想法?为什么它不会取消角色所以我可以使用图像作为路径

4 个答案:

答案 0 :(得分:0)

看来,您确实要关闭2个子目录,然后与\Images\sss.jpg结合使用:

  String source =
    @"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";

  String[] items = source.Split(new Char[] { 
    Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });

  String path = String.Join(
    Path.DirectorySeparatorChar.ToString(), items.Take(items.Length - 2));

  String result = Path.Combine(path, @"Images\sss.jpg");

答案 1 :(得分:0)

您的代码没有任何问题,只要Images目录存在,它就可以正常工作。只需使用

    if (!Directory.Exists(Path.Combine(path, "Images")))
      Directory.Create(Path.Combine(path, "Images")))

答案 2 :(得分:0)

您的代码没有问题:

string source =
    @"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";

string path = source.Substring(0, source.Length - 10);
Console.WriteLine(path); 
//resulting in C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication

....如果

  1. 您将项目构建为“调试”,而不是“发布”
  2. 图像目录和sss.jpg图像确实存在。
  3. 但是,以现在的方式获得路径的方式只是...... 不安全(至少)。请尝试使用Path.Combinestring.Split("\\")代替:

    string source = @"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
    string[] items = source.Split('\\');
    string path = Path.Combine(string.Join("\\", items.Take(items.Length - 2)), "Images\\sss.jpg");
    

答案 3 :(得分:0)

有没有理由不利用DirectoryInfo?看起来你只想上两个目录。您应该能够使用DirectoryInfo.Parent来获取所需的路径,而无需进行字符串操作。

DirectoryInfo startupDirectory = new DirectoryInfo(Application.StartupPath);
DirectoryInfo twoDirectoriesUp = startupDirectory.Parent.Parent;
string fullDirectoryName = twoDirectoriesUp.FullName;