阅读非英文文件

时间:2011-12-11 11:01:01

标签: c# .net

当我尝试读取以阿拉伯语格式编写的文件时,我只得到最后一行......问题是什么。

代码:

// Read the file and display it line by line in text box
System.IO.StreamReader file =
   new System.IO.StreamReader("arabic.txt", Encoding.UTF8);
while ((line = file.ReadLine()) != null)
{
    txtfile[count] = line;
    textBox1.Text = txtfile[count]+Environment.NewLine;

    count++;
}

file.Close();

7 个答案:

答案 0 :(得分:4)

尝试textBox1.Text += txtfile[count]+Environment.NewLine;

答案 1 :(得分:2)

您只看到TextBox中最后一行的原因是因为您没有附加文本。

尝试使用

 textBox1.Text += txtfile[count]+Environment.NewLine;

而不是

textBox1.Text = txtfile[count]+Environment.NewLine;

答案 2 :(得分:1)

你可以试试,

TextBox1.Text=System.IO.File.ReadAllText("arabic.txt",Encoding.UTF8);

答案 3 :(得分:0)

问题是

 textBox1.Text = txtfile[count]+Environment.NewLine

 textBox1.Text += txtfile[count]+Environment.NewLine

答案 4 :(得分:0)

你可以这样尝试

System.IO.StreamReader file = 
       new System.IO.StreamReader("arabic.txt", Encoding.UTF8); 
    while ((line = file.ReadLine()) != null) 
    { 
        txtfile[count] = line; 
        textBox1.Text += txtfile[count]+Environment.NewLine;


        count++; 
    } 

    file.Close(); 

答案 5 :(得分:0)

在您的代码中,您不会将行添加到文本框中,只需设置它即可。所以只显示最后一行。像这样更改你的代码:

// Read the file and display it line by line in text box 
System.IO.StreamReader file = new System.IO.StreamReader("arabic.txt", Encoding.UTF8); 
while ((line = file.ReadLine()) != null) 
{ 
    txtfile[count] = line; 
    textBox1.Text += txtfile[count]+Environment.NewLine; 

    count++; 
} 

file.Close(); 

答案 6 :(得分:0)

就我个人而言,我已将文件读入集合 - 例如List<> - 在将其分配给我的文本框之前,而不是在阅读后直接将其设置为TextBox(TextBox中未显示的所有内容 - 即最后一行之后的所有内容 - 实际上已丢失)。

此外,使用StreamReaders时,请使用using语句;当我们完成后,它会自行消除调用StreamReader.Close()的需要:

public List<string> ReadTextFile(string filePath)
{
    var ret = new List<string>();

    if (!File.Exists(filePath))
        throw new FileNotFoundException();

    // Using the "using" directive removes the need of calling StreamReader.Close
    // when we're done with the object - it closes itself.
    using (var sr = new StreamReader(filePath, Encoding.UTF8))
    {
        var line;

        while ((line = sr.ReadLine()) != null)
            ret.Add(line);
    }

    return ret;
}

您还可以使用数组或任何其他集合。使用它,您可以像这样填充TextBox元素:

var fileContents = ReadTextFile("arabic.txt");

foreach (var s in fileContents)
    textBox1.Text += string.Format("{0}{1}", s, Environment.NewLine);

虽然仍然在fileContents中拥有文本文件的本地副本。

相关问题