使用C#在文本文件中写入文本 [英] Write text in text file using C#

查看:90
本文介绍了使用C#在文本文件中写入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将文本框文本写入文本文件。我不喜欢这个,但它超过我之前的行数据

如何在新行上写新数据?



我是什么尝试过:



 使用(StreamWriter sw1 =  new  StreamWriter( @  D:\ text.txt ))
{
sw1.WriteLine(textBox1.Text);
sw1.Close();
}

解决方案

从.NET Framework 2.0版开始,将文本写入文件变得非常简单:



System.IO工具提供了两种有用的方法:



File.WriteAllText方法 [ ^ ]



File.WriteAllLines方法 [ ^ ]



这两个链接都有现成的代码示例。



这些方法的优点是,与使用此处显示的其他技术不同,它们不会在保存到文件的文本中附加任何额外的字符。



评论:



1.每次将任何内容保存到流或文件中时:在尝试编写/保存之前,请验证您将使用的路径是否有效,可用等。



考虑:如果你希望覆盖它,文件是否已经存在。



2.如果用户要选择保存/写入位置在运行时:花时间研究文件和文件夹选择对话框,以及如何配置它们,以便引导用户进行适当的选择。



3请记住,Text是编码的,可能依赖于文化。计划。


使用 File.AppendText [ ^ ],有很多方法可以做。这是其中一种方式。



 使用(StreamWriter sw1 = File.AppendText( @  D:\ text.txt))
{
sw1.WriteLine(textBox1.Text);
// sw1.Close(); //没必要,因为你正在使用'使用',它会在处理时关闭
}


你可以添加选项追加或者不附加StreamWriter。

 使用(StreamWriter sw1 =  new  StreamWriter( @  D:\ text.txt true ))
{
sw1.WriteLine(textBox1.Text);
sw1.Close();
}





true:在新行上添加新项目。

false:覆盖当前文件


well in to write text box text into text file. i don this but it over ride my previous line data
how can i write new data on new line ?

What I have tried:

using (StreamWriter sw1 = new StreamWriter(@"D:\text.txt"))
            {
                sw1.WriteLine(textBox1.Text);
                sw1.Close();
            }

解决方案

Since version 2.0 of the .NET Framework, writing text to a file is made very easy:

The System.IO facility provides two useful methods:

File.WriteAllText Method [^]

File.WriteAllLines Method [^]

There are ready-to-use code examples at both those links.

These methods have the advantage that, unlike, using the other techniques shown here, they do not append any extra characters to the text saved to the file.

Comments:

1. any time you save whatever to a stream, or file: verify the path you will use is valid, usable, etc., before attempting to write/save.

Consider: if the file already exists if you wish to over-write it.

2. if the user is going to be selecting the save/write location at run-time: take the time to study the File and Folder Selection Dialogs, and how to configure them so the user can be guided to an appropriate choice.

3. keep in mind that Text is encoded, and may be culture-dependent. plan for that.


use File.AppendText[^] , well there are many ways to do. this is one of the way.

using (StreamWriter sw1 = File.AppendText(@"D:\text.txt"))
            {
                sw1.WriteLine(textBox1.Text);
               // sw1.Close(); // not necessary, since you are using 'using', it will close while disposing
            }


You can add option append or not append for StreamWriter.

using (StreamWriter sw1 = new StreamWriter(@"D:\text.txt", true))
{
sw1.WriteLine(textBox1.Text);
sw1.Close();
}



true: add new item on new line.
false: overwrite current file


这篇关于使用C#在文本文件中写入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆