winform中如何读取txt文件并显示

cvily1 2008-07-11 05:24:44
winform中,读取txt文件,并显示在textbox中,遇到2个问题,
1无法显示汉字
2不能完全显示,只能显示部分,我设了多行显示,把textBox2.MaxLength = 99999也不行,也有滚动条,
是不是textBox有默认的最大限制,那我用什么显示比较好?listbox我试了也不行,richtextbox也不行
下面是代码
string path;
path= Path.GetDirectoryName(Application.ExecutablePath) + "\\"+ dataGridView1.CurrentRow.Cells[4].Value .ToString ();
string stype = path.Substring(path.LastIndexOf("."));//上面是路径,没有问题
if (stype == ".txt")
{
if (!File.Exists(path))
{
MessageBox.Show("文件不存在或已经删除");
}
else
{
FileStream fs = File.OpenRead(path);
byte[] arr = new byte[1000];
UTF8Encoding data = new UTF8Encoding(true);

while (fs.Read(arr, 0, arr.Length) > 0)
{
textBox2.Text = data.GetString(arr);
}
}
}
else
{
MessageBox.Show("只能阅读.txt文件,其他文件请下载");
}
...全文
317 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
cvily1 2008-07-12
  • 打赏
  • 举报
回复
1楼和3楼的都可以实现,谢谢了,2楼的也采用了得到path扩展名
cvily1 2008-07-12
  • 打赏
  • 举报
回复


另外读数据改成
byte[] arr = new byte[ 4096 ];
int read = fs.Read( arr, 0, arr.Length );
while ( read > 0 )
{
textBox2.Text = data.GetString( arr,0,read );
read = fs.Read( arr,…
[/Quote]

textBox2.Text = data.GetString( arr,0,read );
这个data是哪来的啊?
yagebu1983 2008-07-11
  • 打赏
  • 举报
回复
顶一楼的!!!!
skison 2008-07-11
  • 打赏
  • 举报
回复
对了 倒不是说用4096就可以 因为 里面可能有数字字母 你无法知道那儿截断了 只是使用read时候一般默认采用4096好点 至少是2^N
lovefootball 2008-07-11
  • 打赏
  • 举报
回复
FileStream fs = File.OpenRead(path);
byte[] arr = new byte[1000];
UTF8Encoding data = new UTF8Encoding(true);

while (fs.Read(arr, 0, arr.Length) > 0)
{
textBox2.Text = data.GetString(arr);
}
---------》


using(StreamReader sr = new StreamReader(path,Encoding.Default))//这里的Encoding是你文本的编码
{
textBox2.Text = sr.ReadToEnd();
}

skison 2008-07-11
  • 打赏
  • 举报
回复
首先 byte[] arr = new byte[1000];
如果是UTF-8 采用1000的byte是不行的 UTF-8汉字长度是3

另外textBox2.MaxLength = 99999不知道是什么意思,
写软件的看到99999 应该想到要么报错,要么长度不为最大

另外读数据改成
byte[] arr = new byte[ 4096 ];
int read = fs.Read( arr, 0, arr.Length );
while ( read > 0 )
{
textBox2.Text = data.GetString( arr,0,read );
read = fs.Read( arr, 0, arr.Length );
}

string stype = path.Substring(path.LastIndexOf("."));
改成System.IO.Path.GetExtension( path ).ToLower();
marvelstack 2008-07-11
  • 打赏
  • 举报
回复
try

string path;
path= Path.GetDirectoryName(Application.ExecutablePath) + "\\"+ dataGridView1.CurrentRow.Cells[4].Value .ToString ();
string stype = path.Substring(path.LastIndexOf("."));//上面是路径,没有问题
if (stype == ".txt")
{
if (!File.Exists(path))
{
MessageBox.Show("文件不存在或已经删除");
}
else
{
FileStream fs = File.OpenRead(path);
StreamReader sr = new StreamReader(fs,Encoding.Default);
textBox2.Text = sr.ReadToEnd();
}
}
else
{
MessageBox.Show("只能阅读.txt文件,其他文件请下载");
}

111,120

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧