Подтвердить что ты не робот

Как записать данные в текстовый файл без перезаписи текущих данных

Я не могу понять, как записать данные в файл без перезаписи. Я знаю, что могу использовать File.appendtext, но я не уверен, как подключить это к моему синтаксису. Вот мой код:

TextWriter tsw = new StreamWriter(@"C:\Hello.txt");

//Writing text to the file.
tsw.WriteLine("Hello");

//Close the file.
tsw.Close();

Я хочу, чтобы он записывал Hello каждый раз, когда я запускаю программу, а не перезаписывал предыдущий текстовый файл. Спасибо, что прочитали это.

4b9b3361

Ответ 2

Измените ваш конструктор, чтобы передать true в качестве второго аргумента.

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);

Ответ 3

Вы должны открыть как new StreamWriter(filename, true), чтобы он добавлялся к файлу вместо перезаписи.

Ответ 4

Здесь фрагмент кода, который будет записывать значения в файл журнала. Если файл не существует, он его создает, иначе он просто добавляется к существующему файлу. Вам нужно добавить "using System.IO;" в верхней части вашего кода, если он еще не существует.

string strLogText = "Some details you want to log.";

// Create a writer and open the file:
StreamWriter log;

if (!File.Exists("logfile.txt"))
{
  log = new StreamWriter("logfile.txt");
}
else
{
  log = File.AppendText("logfile.txt");
}

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();

// Close the stream:
log.Close();

Ответ 5

Лучше всего

File.AppendAllText("c:\\file.txt","Your Text");

Ответ 6

Посмотрите на класс File.

Вы можете создать streamwriter с

StreamWriter sw = File.Create(....) 

Вы можете открыть существующий файл с помощью

File.Open(...)

Вы можете легко добавлять текст с помощью

File.AppendAllText(...);

Ответ 7

Прежде всего проверьте, существует ли имя файла. Если да, то создайте файл и закройте его одновременно, а затем добавьте свой текст с использованием AppendAllText. Для получения дополнительной информации проверьте код ниже.


string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;


 if (!File.Exists(str_Path))
 {
     File.Create(str_Path).Close();
    File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
 else if (File.Exists(str_Path))
 {

     File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }

Ответ 8

using (StreamWriter writer = File.AppendText(LoggingPath))
{
    writer.WriteLine("Text");
}

Ответ 9

I am stuck with some code please help

written the code to reads the few content from the word and writes the data to xml file.

new requirement is 

i need to append these details to existing xml file instead of ovverwritting


HTML:




code behind file:

using Microsoft.Office.Interop.Word;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Table = Microsoft.Office.Interop.Word.Table;


namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            Application app = new Application();
            Document doc = new Document();


            try
            {
                List<string> data = new List<string>();
                WordFileToRead.SaveAs(Server.MapPath(WordFileToRead.FileName));
                object filename = Server.MapPath(WordFileToRead.FileName);

                doc = app.Documents.Open(ref filename);
                foreach (Table tb in doc.Tables)
                {
                    for (int row = 1; row <= tb.Rows.Count; row++)
                    {
                        var cell = tb.Cell(row, 1);
                        var text = cell.Range.Text;

                        var value = tb.Cell(row, 2);
                        var result = value.Range.Text;

                        if (text == "Originator:\r\a")
                        {
                            txtOriginator.Text = result;
                        }
                        else if (text == "Content:\r\a")
                        {
                            txtContent.Text = result;
                        }
                        else if (text == "Begin Date of Message:\r\a")
                        {
                            txtStartDate.Text = result;
                        }
                        else if (text == "End Date of Message:\r\a")
                        {
                            txtEnddate.Text = result;
                        }
                        else if (text == "Parameter (Choose from list, below):\r\a")
                        {
                            txtParameter.Text = result;
                        }
                        else if (text == "*Value/Threshold for Parameter: \r\a")
                        {
                            txtStateCode.Text = result;
                        }
                        else if (text == "Invoice Template (Choose from list below):\r\a")
                        {
                            txtinvoicetemplatelist.Text = result;
                        }

                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                ((_Document)doc).Close();
                ((_Application)app).Quit();
            }



        }

        public void btnSubmit_Click(object sender, EventArgs e)
        {


            string stDate = RemoveInvalidXmlChars(txtStartDate.Text);
            //string formatted = stDate.ToString("ddMMyyyy");
            string endDate = RemoveInvalidXmlChars(txtEnddate.Text);
            string content = RemoveInvalidXmlChars(txtContent.Text);
            string originator = RemoveInvalidXmlChars(txtOriginator.Text);
            string stateCode = RemoveInvalidXmlChars(txtStateCode.Text);
            string param = RemoveInvalidXmlChars(txtParameter.Text);
            string invoiceTemplateList = RemoveInvalidXmlChars(txtinvoicetemplatelist.Text);




            XmlDocument Doc = new XmlDocument();
            XmlDeclaration dec = Doc.CreateXmlDeclaration("1.0", null, null);
            Doc.AppendChild(dec);



            XmlElement DocRoot = Doc.CreateElement("Message");
            Doc.AppendChild(DocRoot);
            XmlAttribute Attr_ID = Doc.CreateAttribute("Id");          
            Attr_ID = Doc.CreateAttribute("Id");

            DateTime time1 = Convert.ToDateTime(stDate);           
            Attr_ID.Value = time1.ToString("yyyymmdd");      
            DocRoot.Attributes.Append(Attr_ID);


            Attr_ID = Doc.CreateAttribute("StartDate");
            DateTime time3 = Convert.ToDateTime(stDate);
            Attr_ID.Value = time3.ToString("yyyymmdd");            
            DocRoot.Attributes.Append(Attr_ID);

            Attr_ID = Doc.CreateAttribute("EndDate");

            DateTime time2 = Convert.ToDateTime(endDate);              
            Attr_ID.Value = time2.ToString("yyyymmdd");
            DocRoot.Attributes.Append(Attr_ID);
            Doc.AppendChild(DocRoot);

            XmlNode conditions = Doc.CreateElement("Conditions");
            DocRoot.AppendChild(conditions);



            XmlNode condition = Doc.CreateElement("Condition");
            XmlAttribute attrcondition = Doc.CreateAttribute("Boolean");
            attrcondition.Value = "AND";
            condition.Attributes.Append(attrcondition);
            conditions.AppendChild(condition);


            XmlNode Parameter = Doc.CreateElement("Parameter");
            XmlAttribute attParam = Doc.CreateAttribute("FieldName");
            attParam = Doc.CreateAttribute("FieldName");
            attParam.Value = "InvoiceDate";
            Parameter.Attributes.Append(attParam);
            attParam = Doc.CreateAttribute("Operator");
            attParam.Value = "GTE";
            Parameter.Attributes.Append(attParam);
            attParam = Doc.CreateAttribute("Value");
            attParam.Value = time3.ToString("yyyymmdd"); 
            Parameter.Attributes.Append(attParam);
            condition.AppendChild(Parameter);

            XmlNode Parameter2 = Doc.CreateElement("Parameter");
            XmlAttribute attParam2 = Doc.CreateAttribute("FieldName");
            attParam2 = Doc.CreateAttribute("FieldName");
            attParam2.Value = "InvoiceDate";
            Parameter2.Attributes.Append(attParam2);
            attParam2 = Doc.CreateAttribute("Operator");
            attParam2.Value = "LTE";
            Parameter2.Attributes.Append(attParam2);
            attParam2 = Doc.CreateAttribute("Value");
            attParam2.Value = time2.ToString("yyyymmdd");
            DateTime time4 = Convert.ToDateTime(endDate);
            Attr_ID.Value = time4.ToString("yyyymmdd");
            Parameter2.Attributes.Append(attParam2);
            condition.AppendChild(Parameter2);


            XmlNode Parameter3 = Doc.CreateElement("Parameter");
            XmlAttribute attParam3 = Doc.CreateAttribute("StateCode");
            attParam3 =Doc.CreateAttribute("FieldName");
            attParam3.Value = "StateCode";
            Parameter3.Attributes.Append(attParam3);
            attParam3 = Doc.CreateAttribute("Operator");
            attParam3.Value = "EQ";
            Parameter3.Attributes.Append(attParam3);
            attParam3 = Doc.CreateAttribute("Value");
            attParam3.Value = "NY";
            Parameter3.Attributes.Append(attParam3);
            condition.AppendChild(Parameter3);

            XmlNode server = Doc.CreateElement("Content");
            DocRoot.AppendChild(server);
            XmlAttribute contentAttr = Doc.CreateAttribute("Class");
            contentAttr.Value = "MarketingMessage";
            server.Attributes.Append(contentAttr);
            XmlNode line = Doc.CreateElement("line");
            server.AppendChild(line);
            line.InnerText = content;


            Doc.Save("C:\\Users\\ab85556\\Desktop\\Message.xml");
            // Doc.Save("C:\\Users\\ab85556\\Desktop\\Message.xml");

            Doc.DocumentElement.AppendChild(DocRoot);

            //adding aattribute to existing xml file

            // C:\\Users\\ab85556\\Desktop\\SaveData.xml


        }

        public static string RemoveInvalidXmlChars(string input)
        {
            return new string(input.Where(value =>
                (value >= 0x0020 && value <= 0xD7FF) ||
                (value >= 0xE000 && value <= 0xFFFD) ||
                value == 0x0009 ||
                value == 0x000A ||
                value == 0x000D).ToArray());
        }
    }

}


output of this code is :
---------------------------------
<?xml version="1.0"?>
<Message Id="20180001" StartDate="20180001" EndDate="20180031">
  <Content Class="MarketingMessage">
    <line>
Effective March 1, 2018, the California Advanced Services Fund (CASF) surcharge will increase from 0.0% to 0.56%. If you have any questions, please call a Customer Care Representative at the telephone number located in the My Account or Important News sections of your bill.

</line>
  </Content>
  <Conditions>
    <Condition Boolean="AND">
      <Parameter FieldName="InvoiceDate" Operator="GTE" Value="20180001" />
      <Parameter FieldName="InvoiceDate" Operator="LTE" Value="20180031" />
      <Parameter FieldName="StateCode" Operator="EQ" Value="NY" />
    </Condition>
  </Conditions>
</Message>

I want to append this content to existing file which has data like 
------------------------------------------------------------------

<Messages>
  <Message Id="01984" Zone="P1_MA_SS_Marketing" Priority="10" StartDate="20050627" EndDate="20050811">
    <Conditions>
      <Condition Boolean="AND">
        <Parameter FieldName="OtherProviderServiceFlag" Operator="EQ" Value="N"/>
        <Parameter FieldName="Buyer" Operator="EQ" Value="Q"/>
        <Parameter FieldName="StateCode" Operator="EQ" Value="OK"/>
      </Condition>
    </Conditions>
    <Content Class="MarketingMessage">
      <Line>Current Charges will be considered Past</Line>
      <Line>
        <Text>Due on </Text>
        <Data FieldName="PastDueDate"/>
      </Line>
    </Content>
  </Message>
  <Message Id="01988" Zone="P1_MA_SS_Marketing" Priority="20" StartDate="" EndDate="">    <Conditions>
      <Condition Boolean="AND">
        <Parameter FieldName="OtherProviderServiceFlag" Operator="EQ" Value="N"/>
        <Parameter FieldName="Buyer" Operator="EQ" Value="Q"/>
        <Parameter FieldName="Partner" Operator="NEQ" Value="AMEX"/>
        <Parameter FieldName="PaymentMethodUsed" Operator="NEQ" Value="CC"/>
        <Parameter FieldName="PaymentMethodUsed" Operator="NEQ" Value="PS"/>
      </Condition>
    </Conditions>
    <Content Class="MarketingMessage">
      <Line>You make the call. CenturyLink allows you to make the bill payment choice that best suits your individual needs. You have the choice of paying your CenturyLink bill by check, money order, Visa, MasterCard, or Discover. Why not explore the convenience and savings of using your credit card to automatically pay your bill each month? To pay your invoice with your credit card or to sign up for recurring billing, please visit https://residential.centurylink.com/account/menu.jsp or call 1-800-860-2255.</Line>
    </Content>
  </Message>
  <Message Id="01990" Zone="P1_MA_SS_Marketing" Priority="25" StartDate="" EndDate="">

    <Conditions>
      <Condition Boolean="AND">
        <Parameter FieldName="OtherProviderServiceFlag" Operator="EQ" Value="N"/>
        <Parameter FieldName="Buyer" Operator="EQ" Value="Q"/>
        <Parameter FieldName="ProductCode" Operator="NEQ" Value="INTLQ5"/>
      </Condition>
    </Conditions>
    <Content Class="MarketingMessage">
      <Line>Save BIG on all your international calls with CenturyLink&apos;s international calling plans. Receive CenturyLink&apos;s lowest international rates 24 hours-a-day, 7 days-a-week! Call today to see how much you can save to the countries you call the most.</Line>
    </Content>
</Message>

  //above message code should come here 


</Messages>