c# - 如何将图像文件保存在我的项目文件夹中?

标签 c# winforms picturebox openfiledialog

在我的 Windows 应用程序中,我有一个 PictureBox 和一个 Button 控件。我想从按钮的 OnClick 事件中加载来自用户的图像文件,并将该图像文件保存在我的项目中名为“proImg”的文件夹中。然后我想在 PictureBox 中显示该图像。

我已经写了这段代码,但它不起作用:

OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (opFile.ShowDialog() == DialogResult.OK)
{
    try
    {
        string iName = opFile.FileName;
        string filepath = "~/images/" + opFile.FileName;
        File.Copy(iName,Path.Combine("~\\ProImages\\", Path.GetFileName(iName)));
        picProduct.Image = new Bitmap(opFile.OpenFile());
    }
    catch (Exception exp)
    {
        MessageBox.Show("Unable to open file " + exp.Message);
    }
}
else
{
    opFile.Dispose();
}

无法将图像保存在“proImg”文件夹中。

enter image description here

最佳答案

实际上 string iName = opFile.FileName; 没有给你完整的路径。您必须改用 SafeFileName。我假设您也希望您的文件夹位于 exe 目录中。请引用我的修改:

OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";

string appPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\ProImages\"; // <---
if (Directory.Exists(appPath) == false)                                              // <---
{                                                                                    // <---
    Directory.CreateDirectory(appPath);                                              // <---
}                                                                                    // <---

if (opFile.ShowDialog() == DialogResult.OK)
{
    try
    {
        string iName = opFile.SafeFileName;   // <---
        string filepath = opFile.FileName;    // <---
        File.Copy(filepath, appPath + iName); // <---
        picProduct.Image = new Bitmap(opFile.OpenFile());
    }
    catch (Exception exp)
    {
        MessageBox.Show("Unable to open file " + exp.Message);
    }
}
else
{
    opFile.Dispose();
}

关于c# - 如何将图像文件保存在我的项目文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21427657/

相关文章:

c# - 从父级在 PictureBox 上画一条线

c# - 自定义 View 中的 BindableProperty 不会取消订阅 PropertyChanged

c# - 通过动态更改字体大小使按钮控件中的文本适合调整大小

c# - DevExpress 皮肤不工作

C# 如何从图片框中获取位图

vb.net - 设置图片框中图像的大小?

c# - MongoDB $first 不支持的错误 C# 驱动程序

c# - 拆分字符串,但忽略方括号或大括号中的定界符

c# - 智能感知显示虚假错误,不能 "go to definition"(Visual Studio 2013)

c# - 如何获得完美的边框并使窗口始终保持在顶部?