我正在尝试在 .exe 文件所在的目录中创建一个文件夹,并将图片保存在该文件夹中。
现在该文件夹不存在,所以我想创建。这是我的代码:
public void SavePictureToFileSystem(string path, Image picture)
{
string pictureFolderPath = path + "\\" + ConfigurationManager.AppSettings["picturesFolderPath"].ToString();
picture.Save(pictureFolderPath + "1.jpg");
}
图像没有保存到 pictureFolderPath 中,而是保存到路径变量中。我需要做什么才能做到这一点?
感谢您的帮助!这就是我最终得到的:
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
,我认为你是这样的好想要。
无论如何,靠Path.Combine
要好得多而不是尝试自己处理组合逻辑。它恰好处理这些类型的极端情况,此外,作为奖励,它与平台无关。
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);
关于c# - 如何将图像保存到文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4087564/