簡體   English   中英

如何將文件寫入.NET Core中的項目文件夾?

[英]How to write a file to a project folder in .NET Core?

我有一個 Web API 項目,它從一些外部 API 調用中獲取數據。 現在,我想將返回的數據作為 json 寫入一個文件,並將該文件放在我項目的一個文件夾中,以便其他調用可以讀取數據。 我必須將它們寫入文件,而不是將信息存儲在 memory 中。

我看過一些使用System.IO寫文件的例子,但都是提到將文件寫到項目外的本地文件系統中。

這樣做的最佳方法是什么?

我正在使用 .NET Core 3.1。

我實際上找到了一個不使用反射的解決方案。 以下是我的代碼:

        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _env;

        const string FileLocation = @"\Files\json.txt";

        public GetTokenController(IConfiguration configuration, IWebHostEnvironment env)
        {
            _configuration = configuration;
            _env = env;
        }

        public async Task<string>WriteFile(string jsonString)
        {
            string contentRootPath = _env.ContentRootPath;
            var logPath = contentRootPath + FileLocation;

            using (StreamWriter streamwriter = System.IO.File.CreateText(logPath))
               {
                   await streamwriter.WriteLineAsync(jsonString);
               }

            return jsonString;
        }

如果我理解得很好,你需要得到你的項目路徑:

如何獲取代碼所在程序集的路徑?

System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location

而不是 DaoTests 將任何 class 名稱放入您的代碼中,該名稱位於您的程序集中。

比您可以使用 System.IO.File.WriteAllText 保存文件

我建議您在項目路徑中至少創建一個子文件夾。 通常,沒有理由將數據存儲到項目的“二進制文件夾”中。 在某個地方創建“數據文件夾”並使用此路徑。

暫無
暫無

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

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