簡體   English   中英

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

[英]How to Get File using Console application in 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());
            }
        }
    }
}

當我運行另一個我的localhost的ASP.NET應用程序時,它只返回Controller中的value1和value2的默認值。 但是,我在C#控制台應用程序中沒有Controller。 我想我只有一步之遙,我已成功獲取文件和CopyToAsync我想下載的文件。

結論:我希望當用戶運行應用程序時,它會直接在一個地方下載文件(或者我可以使用SaveFileDialog讓用戶決定保存文件的位置)。 請幫助謝謝

更新:

首先,我創建了一個ASP.NET Web應用程序並創建了一個PersonController,然后運行了Project。 之后我創建了一個控制台C#應用程序然后我想實現用戶運行控制台時的結果C#Application它會直接將文件下載到特定的地方。

在第一次獲取我使用api / person,我將文件轉換為int o bytes數組並將bytes數組添加到內存流中。 在那之后,我真的不知道我在做什么是對還是錯。 我看到像CopyToAsync這樣的東西正在工作然后我嘗試並實現它但它不會工作。 我的目標很簡單我只想在運行C#Console應用程序后實現它會直接從特定的localhost地址下載文件

好吧我認為你的問題是你發送了兩個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();
    }

希望這很有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM