日期:2014-05-18  浏览次数:20916 次

C# 关于读取文件的问题?各位老师请帮忙
private void btuDu_Click(object sender, EventArgs e)
  {
  //声明变量
  string path;
  //接收要读取的文件名路径
  path = txtNames.Text;

  try
  {
  //判断文件是否存在
  if (!File.Exists(path))
  {
  MessageBox.Show("文件不存在");
  }
  else
  {
  //打开流以进行读取
  FileStream fa = File.OpenRead(path);
  //把读取到的数据存放在arr []中,并在txtName.Text文本框显示
  byte[] arr = new UTF8Encoding(true).GetBytes(txtName.Text);
  //byte[] arr = new byte[1000];
  // UTF8Encoding data = new UTF8Encoding(true);
  //一直到读完
  while(fa.Read(arr,0,arr.Length)>0)
  {
  MessageBox.Show("dddd");
  }
  }
  }
  catch(Exception ex)
  {
  MessageBox.Show("出现错误"+ex.Message);
  }
  }
  }

我这样读取文件,即不报错又不成功,
错在那里呢????

------解决方案--------------------
byte[] arr = new UTF8Encoding(true).GetBytes(txtName.Text);
这句是将读取的内容在 txtName.Text文本框显示
----------------------------------
txtName.Text是你要赋值的对象,
Encoding.GetBytes(string)string是个传入的进行字节编码的参数。
逻辑错误。
----
using System;
using System.IO;

class Test 
{
public static void Main() 
{
try 
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
String line;
// Read and display lines from the file until the end of 
// the file is reached.
while ((line = sr.ReadLine()) != null) 
{
Console.WriteLine(line);
}
}
}
catch (Exception e) 
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}