我正在尝试在.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"));
}
答案 0 :(得分:6)
我怀疑你的问题是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);
答案 1 :(得分:1)
我怀疑ConfigurationManager.AppSettings["picturesFolderPath"].ToString()
可能为空,因此pictureFolderPath
变量仅设置为path
值。确保设置正确并返回值。在该行上放置一个断点并在Watch / Immediate窗口中检查它。
答案 2 :(得分:0)
您可以先尝试创建目录:
Directory.CreateDirectory(pictureFolderPath);