保存在 C# 中程序员定义的文件夹中

发布于 2024-08-22 18:01:30 字数 269 浏览 3 评论 0原文

我正在尝试将图片保存在项目的相对路径中。我希望它位于名为“images”的文件夹中。通过使用这段代码,

theImage.Save("\\images\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

我通过使用绝对路径进行测试意识到,文件夹“images”必须存在才能工作。问题是,我不知道项目的根文件夹是什么,所以我可以在 Windows 资源管理器中手动创建该文件夹。我该如何解决我的问题?

I'm trying to save a picture in a relative path of my project. I want it to be in a folder called "images". By using this code

theImage.Save("\\images\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

I realized by testing with an absolute path, that the folder "images" must exist for it to work. problem is, I don't know what the root folder for the project is, so I can manually create the folder in windows explorer. how can I fix my problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自由范儿 2024-08-29 18:01:30
Directory.Create("images");
theImage.Save(@"images\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

Directory.Create 只会在文件夹尚不存在时创建一个文件夹,因此无需担心这一点。字符串文字之前的 @ 使得唯一需要转义的字符是 " ,其完成方式类似于 ""。无论如何,我认为您现在不必手动创建自己的文件夹。此外,为了将来的参考,您可以使用 Environment.CurrentDirectory 以编程方式获取当前工作目录:

在这种情况下,尝试:

Directory.CreateDirectory("images");  
string path = Path.Combine(Environment.CurrentDirectory, @"images\image.jpg";
theImage.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);`
Directory.Create("images");
theImage.Save(@"images\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

Directory.Create will only make a folder if one does not yet exist, so no need to worry about that. The @ before a string literal makes it so that the only character that needs to be escaped is the " which is done like "". Anyways, I don't think you should have to make your own folder manually now. Also, for future reference, you can get the current working directory programmatically by using Environment.CurrentDirectory.

EDIT: In that case, try:

Directory.CreateDirectory("images");  
string path = Path.Combine(Environment.CurrentDirectory, @"images\image.jpg";
theImage.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文