如何在Asp.net Core应用程序中创建文本文件

问题描述 投票:0回答:2

我是新来的Dot-net核心应用程序,如何在Asp.net核心应用程序中创建文本文件,请提供一些资源

asp.net-core .net-core asp.net-core-mvc asp.net-core-2.1 asp.net-core-mvc-2.1
2个回答
0
投票

与经典.NET几乎相同

using System;
using System.IO;


        string path= Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        using (StreamWriter outputFile = new StreamWriter(Path.Combine(path, "myfile.txt")))
        {
                outputFile.WriteLine("Hello world!");
        }

希望有帮助。


0
投票

如何在Asp.net Core应用程序中创建文本文件

如果要在ASP.NET Core MVC项目的特定文件夹中创建文本文件,则可以参考以下代码片段。

public class HomeController : Controller
{
    private IHostingEnvironment _env;

    public HomeController(IHostingEnvironment env)
    {
        _env = env;
    }

    public IActionResult Index()
    {
        var path = Path.Combine(_env.ContentRootPath, @"TxtFiles\" + "MyTest.txt");

        using (FileStream fs = System.IO.File.Create(path))
        {
            byte[] content = new UTF8Encoding(true).GetBytes("Hello World");

            fs.Write(content, 0, content.Length);
        }

        //code logic here
        //...

        return View();
    } 

用于保存文本文件的文件夹TxtFiles

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.