1

OpenDialog我的wpf 应用程序中有一个,用户可以在其中选择文件并保存到文件夹。我想将图像保存到特定文件夹并在 wpf 中单击按钮设置文件名和扩展名。

文件夹结构:

  • -MyAppDirectory
    --ContactImages

    -1.jpg

当我执行以下代码时,它会ContactImages在 Bin 文件夹中创建“”目录,而不是在应用程序主目录中。任何想法?& 如何在 wpf 中获取上传文件的文件扩展名并设置文件名?

在 xaml.cs 文件中:

private void imgContactImage_MouseDown(object sender, MouseButtonEventArgs e)
        {

            string folderpath = Environment.CurrentDirectory + "\\ContactImages\\";
            op.Title = "Select a picture";
            op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";

            bool? myResult;
            myResult = op.ShowDialog();
            if (myResult != null && myResult == true)
            {

                imgContactImage.Source = new BitmapImage(new Uri(op.FileName));
                if (!Directory.Exists(folderpath))
                {
                    Directory.CreateDirectory(folderpath);
                }

                //System.IO.File.Copy(op.FileName,filename);
            }
}
4

1 回答 1

7

您可以将提供的代码段重写为

OpenFileDialog op = new OpenFileDialog();
string folderpath = System.IO.Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\ContactImages\\";
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
            "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
            "Portable Network Graphic (*.png)|*.png";

bool? myResult;
myResult = op.ShowDialog();
if (myResult != null && myResult == true)
{
  imgContactImage.Source = new BitmapImage(new Uri(op.FileName));
  if (!Directory.Exists(folderpath))
  {
     Directory.CreateDirectory(folderpath);
  }
  string filePath = folderpath + System.IO.Path.GetFileName(op.FileName);
  System.IO.File.Copy(op.FileName, filePath, true);
 }
于 2013-07-08T08:40:43.987 回答