如何将映像保存到文件系统? [英] How can I save an Image to the File System?

查看:101
本文介绍了如何将映像保存到文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在.exe文件所在的目录中创建一个文件夹,并将图片保存在该文件夹中.

I'm trying to create a folder on the directory where the .exe file is and save a picture in that folder.

现在该文件夹不存在,所以我想创建一个.这是我的代码:

Right now that folder doesn't exist so I'd like to be created. Here's the code I have:

public void SavePictureToFileSystem(string path, Image picture)
{
    string pictureFolderPath = path + "\\" + ConfigurationManager.AppSettings["picturesFolderPath"].ToString();
    picture.Save(pictureFolderPath + "1.jpg");
}

图像不会保存到pictureFolderPath中,而是保存到path变量中.我需要完成什么?

The Image isn't being saved to the pictureFolderPath but to the path variable. What do I need to accomplish this?

感谢您的帮助!这就是我最终得到的:

Thanks for the help! This is what I ended up with:

public void SavePictureToFileSystem(string path, Image picture)
{
    var pictureFolderPath = Path.Combine(path, ConfigurationManager.AppSettings["picturesFolderPath"].ToString());
    if (!Directory.Exists(pictureFolderPath))
    {
        Directory.CreateDirectory(pictureFolderPath);
    }

    picture.Save(Path.Combine(pictureFolderPath, "1.jpg"));
}

推荐答案

怀疑您的问题是ConfigurationManager.AppSettings["picturesFolderPath"].ToString()返回的文件夹路径为空,或者更可能不是以结尾后面的反斜杠.这意味着最终构造的路径最终看起来像c:\dir1.jpg而不是c:\dir\1.jpg,这是我认为您真正想要的.

I suspect your problem is that ConfigurationManager.AppSettings["picturesFolderPath"].ToString() returns a folder-path that is empty or, more likely, does not end with a trailing back-slash. This would mean that the final constructed path would end up looking like c:\dir1.jpg rather than c:\dir\1.jpg, which is what I think you really want.

无论如何,最好依靠 Path.Combine ,而不是亲自尝试处理合并逻辑.它恰好处理了这类极端情况,此外,它是与平台无关的,这是一个额外的奖励.

In any case, it's much better to rely onPath.Combinethan to try to deal with the combining logic yourself. It deals with precisely these sorts of corner-cases, plus, as a bonus, it's platform-independent.

var appFolderPath = ConfigurationManager.AppSettings["picturesFolderPath"]
                                        .ToString();

// This part, I copied pretty much verbatim from your sample, expect
// using Path.Combine. The logic does seem a little suspect though.. 
// Does appFolder path really represent a subdirectory name?
var pictureFolderPath = Path.Combine(path, appFolderPath);

// Create folder if it doesn't exist
Directory.Create(pictureFolderPath);

// Final image path also constructed with Path.Combine
var imagePath = Path.Combine(pictureFolderPath, "1.jpg")
picture.Save(imagePath);

这篇关于如何将映像保存到文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆