我正在尝试在.exe文件所在的目录上创建一个文件夹,并将图片保存在该文件夹中.
现在该文件夹不存在所以我想创建.这是我的代码:
public void SavePictureToFileSystem(string path, Image picture)
{
string pictureFolderPath = path + "\\" + ConfigurationManager.AppSettings["picturesFolderPath"].ToString();
picture.Save(pictureFolderPath + "1.jpg");
}
Run Code Online (Sandbox Code Playgroud)
Image不会保存到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"));
}
Run Code Online (Sandbox Code Playgroud)
我怀疑你的问题是 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);
Run Code Online (Sandbox Code Playgroud)