如何在C#中使用控制台应用程序获取文件?

时间:2019-04-22 07:05:39

标签: c#

我正在为GET文件构建一个C#控制台应用程序,当我运行控制台应用程序时,它将自动下载该文件。

这些是我的代码:

using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace WebAPIConsoleNEW
{
    class Program
    {


        static void Main(string[] args)
        {
            RunAsync().Wait();
        }

        static async Task RunAsync()
        {
            string bookPath_Pdf = @"D:\VisualStudio\randomfile.pdf";
            string bookPath_xls = @"D:\VisualStudio\randomfile.xls";
            string bookPath_doc = @"D:\VisualStudio\randomfile.docx";
            string bookPath_zip = @"D:\VisualStudio\randomfile.zip";

            string format = "pdf";
            string reqBook = format.ToLower() == "pdf" ? bookPath_Pdf : (format.ToLower() == "xls" ? bookPath_xls : (format.ToLower() == "doc" ? bookPath_doc : bookPath_zip));
            string fileName = "sample." + format.ToLower();

            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:49209/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("applicaiton/json"));

                    Console.WriteLine("GET");

                    //converting Pdf file into bytes array
                    var dataBytes = File.ReadAllBytes(reqBook);

                    //adding bytes to memory stream
                    var dataStream = new MemoryStream(dataBytes);

                    //send request asynchronously
                    HttpResponseMessage response = await client.GetAsync("api/person");
                    response.Content = new StreamContent(dataStream);
                    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = fileName;
                    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

                    //Check that response was successful or throw exception
                    //response.EnsureSuccessStatusCode();

                    //Read response asynchronously and save asynchronously to file
                    if (response.IsSuccessStatusCode)
                    {
                        using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:49209/api"))
                        {
                            using (
                            Stream contentStream = await (await client.SendAsync(request)).Content.ReadAsStreamAsync(),
                                fileStream = new FileStream("D:\\VisualStudio\\randomfile.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                                //copy the content from response to filestream
                                await response.Content.CopyToAsync(fileStream);
                                //Console.WriteLine();
                            }   

                        }
                    }

            }
            catch (HttpRequestException rex)
            {
                Console.WriteLine(rex.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

当我运行另一个ASP.NET应用程序(即我的本地主机)时,它仅返回Controller中的默认值value1和value2。但是,我在C#控制台应用程序中没有控制器。我想离我只有一步之遥,我已经成功获取了文件,并且CopyToAsync我想要下载的文件。

结论: 我希望当用户运行该应用程序时,可以直接将文件下载到某个位置(或者我可以使用SaveFileDialog来让用户决定将文件保存在何处)。 请帮助谢谢

更新

首先,我创建了一个ASP.NET Web应用程序并创建了一个PersonController,然后运行该项目。之后,我创建了一个控制台C#应用程序,然后我想获得当用户运行控制台C#应用程序时将文件直接下载到特定位置的结果。

在第一个获取中,我使用api / person,然后将文件转换为字节数组,并将字节数组添加到内存流中。在那之后,我真的不知道我在做什么是对还是错。我看到类似CopyToAsync的东西正在工作,然后尝试并实现了它,但是它不起作用。我的目标很简单,我只想在运行C#Console应用程序后即可从特定的本地主机地址直接下载文件

1 个答案:

答案 0 :(得分:0)

好吧,我认为您的问题是,您正在发送两个GET请求,以防您只想调用api/student然后将响应保存到文件中,而无需第二个请求

var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:49209/api")//no need for it

所以您的代码应如下所示:

static async Task RunAsync()
    {
        string bookPath_Pdf = @"D:\VisualStudio\randomfile.pdf";
        string bookPath_xls = @"D:\VisualStudio\randomfile.xls";
        string bookPath_doc = @"D:\VisualStudio\randomfile.docx";
        string bookPath_zip = @"D:\VisualStudio\randomfile.zip";

        string format = "pdf";
        string reqBook = format.ToLower() == "pdf" ? bookPath_Pdf : (format.ToLower() == "xls" ? bookPath_xls : (format.ToLower() == "doc" ? bookPath_doc : bookPath_zip));
        string fileName = "sample." + format.ToLower();

        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:49209/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("applicaiton/json"));

                Console.WriteLine("GET");

                //converting Pdf file into bytes array
                var dataBytes = File.ReadAllBytes(reqBook);

                //adding bytes to memory stream
                var dataStream = new MemoryStream(dataBytes);

                //send request asynchronously
                HttpResponseMessage response = await client.GetAsync("api/person");
                response.Content = new StreamContent(dataStream);
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = fileName;
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

                //Check that response was successful or throw exception
                //response.EnsureSuccessStatusCode();

                //Read response asynchronously and save asynchronously to file
                if (response.IsSuccessStatusCode)
                {
                    using (Stream contentStream = await response.Content.ReadAsStreamAsync())
                    {
                        using (fileStream = new FileStream("D:\\VisualStudio\\randomfile.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            //copy the content from response to filestream
                            await response.Content.CopyToAsync(fileStream);
                            //Console.WriteLine();
                        }   
                    }
                }
           }
        }
        catch (HttpRequestException rex)
        {
            Console.WriteLine(rex.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

最好为用户打印一条消息,告诉他正在将数据从服务器记录到文件(文件路径)中。

    static void Main(string[] args)
    {
        Console.WriteLine("Logging data from server into file (D:\\VisualStudio\\randomfile.pdf");
        RunAsync().Wait();
    }

希望这很有用