简体   繁体   English

C#-文本框中的ReadLine()

[英]C# - ReadLine() in a textbox

I'm sorry for asking noobish questions, but I am one :). 我很抱歉提出这个笨拙的问题,但我是一个:)。

I can write a .txt file using Write or WriteLine, which reads the whole TextBox. 我可以使用Write或WriteLine编写一个.txt文件,该文件读取整个TextBox。 The problem is when I read it. 问题是当我阅读它时。 I can not read it using ReadLine. 我无法使用ReadLine读取它。 It gives the whole text on one line. 它把整个文本放在一行上。 It must be a problem with the reading, because in NotePad, I get the file correctly. 读取一定有问题,因为在NotePad中,我可以正确获取文件。

What is the reason of this quite strange behavior, and how can I change it? 这种异常行为的原因是什么,我该如何更改? method containing StreamReader 包含StreamReader的方法

StreamReader streamreader = new StreamReader(openfiledialog.FileName);

textbox.Text = "";

while (!streamreader.EndOfStream)
{
    string read_line = streamreader.ReadLine();
    textbox.Text += read_line + "\n";
}

streamreader.Close();

method containing StreamWriter 包含StreamWriter的方法

StreamWriter streamwriter = new StreamWriter(savefiledialog.FileName);

streamwriter.Write(textbox.Text);

streamwriter.Close();

Thanks in advance. 提前致谢。

UPDATED: ReadToEnd worked 更新:ReadToEnd工作

Without seeing any code the best guess I have is you're using different line separators between the textbox and the text file. 没有看到任何代码,我的最佳猜测是您在文本框和文本文件之间使用了不同的行分隔符。

I'd guess you either need to format the data to make sure the data gets the right separator for the source, or change the newline separator for the textbox. 我猜您可能需要格式化数据以确保数据获得源的正确分隔符,或者更改文本框的换行符。

Couple of possibilities here. 这里有几种可能性。

  1. The text in the File is not UTF-8, so it needs to be converted to UTF-8 and then assigned to the text box. 文件中的文本不是UTF-8,因此需要将其转换为UTF-8,然后分配给文本框。
  2. The Textbox has a character limit that needs to be increased 文本框有一个字符限制,需要增加
  3. Width of Text Box. 文本框的宽度。 Wrapping of text could make a difference. 包装文字可能会有所作为。

Usually you would use ReadToEnd if you want the whole file worth of text in one run and ReadLine if you want 1 line. 通常,如果您希望一次运行整个文件中的文本值,则使用ReadToEnd;而如果您希望一行则需要ReadLine。 Difference here is in the encoding of the file. 此处的区别在于文件的编码。 1 Line in a text editor could be different from another. 1文本编辑器中的一行可能与另一行不同。 Some Text Editor convert the text to other encodings and some do not, before displaying. 在显示之前,有些“文本编辑器”会将文本转换为其他编码,而有些则没有。 Would recommed Notepad++, because it will tell you at the bottom what encoding the file is in and let you change the encoding and save the file for testing. 建议使用Notepad ++,因为它会在底部告诉您文件的编码格式,并让您更改编码并保存文件以进行测试。

.net is based on UTF-8 encoding for strings, so a difference in ecoding of text could make a big difference. .net基于字符串的UTF-8编码,因此文本的编码差异可能会产生很大的不同。

Best of Luck 祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM