[英]Save image from URL to local hard drive using C#
Im trying to write a console application in order to store a single image from a given path into a new directory as suggested in this article . 我试图编写一个控制台应用程序,以将给定路径中的单个图像存储到本文建议的新目录中。 Despite my program not throwing out any errors the image I want to download just won't show up in my folder. 尽管我的程序没有抛出任何错误,但我要下载的图像仍不会显示在我的文件夹中。 I guess that's because I never told my program where I want the file to be saved? 我想那是因为我从未告诉过我的程序我希望文件保存在哪里? However, I haven't found anything clarifying this particular problem I have right now. 但是,我还没有发现任何东西可以澄清我现在遇到的这个特殊问题。 I already referred to this and this question, too. 我已经提到这个和这个问题了。
using System;
using System.IO;
using System.Net;
namespace GetImages
{
class Program
{
static void Main(string[] args)
{
string dirPath = @"C:\Users\Stefan\Desktop\Images";
try
{
// Create a new directory
DirectoryInfo imageDirectory = Directory.CreateDirectory(dirPath);
Console.WriteLine($"Directory '{Path.GetFileName(dirPath)}' was created successfully in {Directory.GetParent(dirPath)}");
// Image I'm trying to download from the web
string filePath = @"http://ilarge.lisimg.com/image/12056736/1080full-jessica-clements.jpg";
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.GetFileName(filePath));
_wc.Dispose();
}
Console.WriteLine("\nFile successfully saved.");
}
catch(Exception e)
{
while (e != null)
{
Console.WriteLine(e.Message);
e = e.InnerException;
}
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
}
}
}
} }
Edit: After some time I figured out that the file is saved in "C:\\Users\\Stefan\\Documents\\Visual Studio 2017\\Projects\\GetImages\\GetImages\\bin\\Debug"
. 编辑:一段时间后,我发现该文件保存在"C:\\Users\\Stefan\\Documents\\Visual Studio 2017\\Projects\\GetImages\\GetImages\\bin\\Debug"
。 But how do I get the file to be saved directly to dirPath
without moving them from Debug
to dirPath
separately? 但是,如何将文件直接保存到dirPath
而不将它们分别从Debug
移到dirPath
? My next step would be extending this program to save multiple files at once. 我的下一步是扩展该程序以一次保存多个文件。
DownloadFileAsync的第二个参数是保存位置,因此请结合您创建的路径和URL中的文件名:
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath, Path.GetFileName(filePath)));
Try this: 尝试这个:
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath,Path.GetFileName(filePath)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.