Write to a text file

自古美人都是妖i 提交于 2019-12-13 15:30:49

问题


I am looking for a way to write to a text file in C#. I have created a form that has a textbox for firstname, lastname, phone number, date of birth. When a user hits the button I would like that info wrote out to a text file. The examples I have found don't really tell me how. So that's why I am asking on here.


回答1:


The very simplest way is just to use File.WriteAllText. Build the text into a single string however you want to, then use

File.WriteAllText(filename, text);

Alternatively you can open a TextWriter on the file to do it bit by bit:

using (TextWriter writer = File.CreateText(filename)) // Or AppendText
{
    writer.WriteLine("First name: {0}", firstNameInput.Text);
    writer.WriteLine("Last name: {0}", lastNameInput.Text);
    writer.WriteLine("Phone number: {0}", phoneInput.Text);
    writer.WriteLine("Date of birth: {0}", birthInput.Text);
}

Note that you may want to be more cunning about the date of birth than just dumping the text directly from the user - you may want to validate it and write it in a standard format, for example.




回答2:


Inside a ButtonClick or similar:

using (var writer = System.IO.File.CreateText(fileName))
{
    writer.WriteLine(firstNametextbox.Text);
    // other writes
}


来源:https://stackoverflow.com/questions/4138779/write-to-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!