学习型 ASP/PHP/ASP.NET 主机 30元/年全能 ASP/PHP/ASP.NET 主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付
发新话题
打印

c#写记事本问题

c#写记事本问题

相信学c#的人都开始学习用c#写记事本的
但是我写的时候发现一个问题
不是很懂   请教下高手
private void OpenFile(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
            byte[] array = new byte[10000000];或者byte[] array = new byte[1024];
            int length;
            while ((length = fs.Read(array, 0, array.Length)) > 0)
            {
                string s = System.Text.Encoding.Default.GetString(array, 0, length);
                textBox1.AppendText(s);
            }
就是写记事本读取内容的部分,用到了数组,数组设置的越大,打开要显示的内容的时候就不用循环那么多次来显示内容了。但别人说这里存在一个浪费空间问题,我不是很懂
我举个例子:比如要打开10000000大小的内容,我设置的数组byte[] array = new byte[10000000];刚好一样大,这样会浪费空间么?
如果我要打开1024字节,
我声明了byte[] array = new byte[10000000];时  ,是怎么个浪费空间?

TOP

一样大不会,多了的话你就浪费了 100000000 - 1024 那么多的 byte 了...

你可以用分页的方式 + 预读取来处理,比如 16K 一页,又有效率又节约

TOP

public void OpenFile(string fileName)
        {
            FileStream fs=null;
            StreamReader sr = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                sr = new StreamReader(fs, System.Text.Encoding.Default);
                contenttextBox.AppendText(sr.ReadToEnd());
                _editFileName = fileName;
               
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开文件出错\r\n" + ex.Message);
               
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

TOP

这是我的记事本的openfile代码,你可以看一下

TOP

发新话题