标题:C#读写文件异常,出现文件写不进去,或软件自动关闭,出现"变量未定义"等不同现 ...
只看楼主
song_dx
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2012-3-5
结帖率:0
已结贴  问题点数:20 回复次数:1 
C#读写文件异常,出现文件写不进去,或软件自动关闭,出现"变量未定义"等不同现象.
用c#读取TCP/IP传过来的数据包,数据量较大,对多个文件进行多写操作.

运行一段时间后,出现软件自动关闭,或打开文件时数据丢失,软件报错等现象.

请看看有什么好的建议.

 private void writeFile()
        {
            //Monitor.Enter(this);//锁定,保持同步
            int i = 0;
            int j = 0;
            int k = 0;//长度  
           // try
           // {
            while (i < chnnm.Count)
            {
                path1 = Application.StartupPath + "\\dats\\" + chnnm[i].devs.ToString() + "-" + chnnm[i].numb.ToString() + " " + chnnm[i].fime;
                if (File.Exists(path1))//工作状态并且文件存在
                {

                    byte[] bf = new byte[910];
                    j = 0;
                    k = 0;//长度   
                    while (j < datrm.Count)
                    {
                        if (k >= 900)
                        {
                            MessageBox.Show("k>=900");
                            break;
                        }
                        if ((datrm[j][0] == (byte)chnnm[i].devs) && (datrm[j][1] == (byte)chnnm[i].numb))
                        {
                            bf[k++] = datrm[j][2];
                            bf[k++] = datrm[j][3];
                            bf[k++] = datrm[j][4];
                            datrm.Remove(datrm[j]);
                            continue;      //删除当前记录后,不要执行j++;
                        }
                        j++;
                    }
                    if (k != 0)
                    {
                        FileStream fs = new FileStream(path1, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                        fs.BeginWrite(bf, 0, k, new AsyncCallback(WriteDone), fs);

                        // fs.Write(bf, 0, k);
                        // Thread.Sleep(200);
                    }
                }
                i++;
            }
          //  }
          //  catch { MessageBox.Show("错误"); }
            //Monitor.Exit(this);//取消锁定
        }
搜索更多相关主题的帖子: 软件 private 数据包 
2012-03-05 09:49
Jian_X
Rank: 4
等 级:业余侠客
威 望:1
帖 子:51
专家分:212
注 册:2009-10-23
得分:20 
文件写完后,把fs关闭掉,fs.Dispose();
2012-03-05 19:42



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-362236-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.090788 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved