【问题标题】:How to write to a text file without overwriting the text that already exists? [duplicate]如何写入文本文件而不覆盖已经存在的文本? [复制]
【发布时间】:2021-07-19 08:15:33
【问题描述】:

我需要创建一个名为 publish 的方法,以 JSON 格式获取名称、描述、端点、操作数和操作数类型,并将其写入文本文件。我已经实现了该部分,但是在第一次 API 调用之后,文本文件中的文本被覆盖,这不是我想要的。我在下面包含了模型类和控制器类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

namespace Registry.Models
{
    public class publishModel
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string endpoint { get; set; }
        public int NoOfoperands { get; set; }
        public string operandType { get; set; }
    }
}


using Newtonsoft.Json;
using Registry.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Web.Http;

namespace Registry.Controllers
{
    public class publishController : ApiController
    {

        [Route("api/publish")]
        [HttpPost]
        public string publish(publishModel pModel)
        {
            string servicePath = @"C:\Users\ASUS\source\repos\DC assignment 1\Services.txt";


            MemoryStream ms = new MemoryStream();
            var write = new Utf8JsonWriter(ms);

            write.WriteStartObject();
            write.WriteString("Name", pModel.Name);
            write.WriteString("Description", pModel.Description);
            write.WriteString("Endpoint", pModel.endpoint);
            write.WriteString("No of operands", pModel.NoOfoperands.ToString());
            write.WriteString("Operand type", pModel.operandType);
            write.WriteEndObject();
            write.Flush();

            string json = Encoding.UTF8.GetString(ms.ToArray());
            //string json = JsonConvert.SerializeObject(pModel);

            try
            {
                using (StreamWriter writer = new StreamWriter(servicePath))
                {
                    writer.Write(json);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return "Description saved";
        }

     
        
    }
}

【问题讨论】:

  • 你真正想要的是什么?通常,要附加到文件,您必须使用正确的标志创建 StreamWriter。见stackoverflow.com/questions/7306214/…。但是,如果您正在编写 JSON,那么将新的 JSON 附加到其中已经包含 JSON 或包含其他任何内容的文件可能没有用。

标签: c# asp.net-web-api


【解决方案1】:

https://docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=net-5.0#System_IO_StreamWriter__ctor_System_String_System_Boolean_

为您的 StreamWriter 添加一个额外的参数:

using (StreamWriter writer = new StreamWriter(servicePath, true))

这告诉它您打开写入路径,但附加到文件。当你不传入一个布尔值(这就是你正在做的)时,它默认覆盖文件。

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2020-03-28
    • 2011-05-08
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多