使用FileStream处理任何文件,我先用FileStream读取一个文件,这个文件可以是txt,也有可能是xml,也有可以是doc等等文件,然后分批读取出来存储到一个文件类对象的队列类型的属性里,再循环这个队列,将数据重新写入到新建的同类型的文件中,但是新文件的内容是乱码,请问这个是怎么回事,要如何解决?
下面是我的代码://这个是一个文件操作类FileManagor 
/// <summary>
        /// 获取传输的文件对象。
        /// </summary>
        /// <returns>传输的文件对象</returns>
        public FileInstance GetFileData()
        {
            try
            {
                FileInstance instance = new FileInstance();
                string FileFullName = this._Path.Substring(this._Path.LastIndexOf('\\'));
                string[] fileInfo = FileFullName.Split('.');
                instance.FileName = fileInfo[0];
                instance.Extension = fileInfo[1];
                instance.StartPosition = 0;                FileStream fs = new FileStream(this._Path, FileMode.Open);
                //当前读取的文件长度
                long fileLength = fs.Length;
                instance.Length = fileLength;                //临时存储数据缓存
                byte[] byteDate=new byte[200];
                //每次读取的最大数据长度
                int maxLength = byteDate.Length;                //文件开始读取的位置
                int start = 0;
                //实际每次读取返回的文件数据长度
                int num = 0;
                //开始读取文件数据
                while (fileLength > 0)
                {
                    fs.Position = start;
                    if (fileLength < maxLength)
                    {
                        num = fs.Read(byteDate, 0, Convert.ToInt32(fileLength));
                    }
                    else
                    {
                        num = fs.Read(byteDate, 0, maxLength);
                    }
                    start += num;
                    fileLength -= num;
                    instance.FileData.Enqueue(byteDate);
                }                fs.Flush();
                fs.Close();
                fs.Dispose();                return instance;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }        /// <summary>
        /// 将文件对象进行写入到新文件
        /// </summary>
        /// <param name="instance">传输的文件对象</param>
        public void UploadFileData(FileInstance instance)
        {
            try
            {
                FileInstance newInstance = new FileInstance();
                newInstance.FileName = Guid.NewGuid().ToString().Replace("-", "");
                newInstance.Extension = instance.Extension;
                newInstance.Length = instance.Length;
                newInstance.StartPosition = instance.StartPosition;
                newInstance.LastPosition = instance.LastPosition;                string dir = string.Format("{0}\\{1}", AppDomain.CurrentDomain.BaseDirectory, "Upload");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                string path = string.Format("{0}\\{1}.{2}", dir, newInstance.FileName, instance.Extension);
                FileStream fs = new FileStream(path, FileMode.Append);
                
                long fileLength = instance.Length;
                
                Queue<byte[]> tmp = instance.FileData;
                foreach (byte[] arrByte in tmp)
                {
                    if (fileLength < arrByte.Length)
                    {
                        fs.Write(arrByte, 0, Convert.ToInt32(fileLength));
                    }
                    else
                    {
                        fs.Write(arrByte, 0, arrByte.Length);
                    }
                }
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }//客户端调用的代码
FileManagor fileor = new FileManagor("F:\\PluginSample\\UpgradeLog.XML");
FileInstance obj = fileor.GetFileData();
fileor.UploadFileData(obj);

解决方案 »

  1.   

    用StreamReader, Writer来读写,而且指定编码。
      

  2.   

    本帖最后由 bdmh 于 2011-06-06 16:56:34 编辑
      

  3.   

    to bdmh
       我觉得应该是和编码有关系的,但是FileStream不是应该可以读写任何文件的吗,我读取的时候是将一个文件拆成多个byte按顺序存放到instance.FileData中的,然后再将instance这个对象传给写入方法UploadFileData,在UploadFileData中按顺序取出数据分批写入新建的文件中,我调试查看文件长度是一致的
      

  4.   

    FileStream是按二进制读取,但是你文件的编码不同,它的自身的二进制也不一样啊,比如unicode编码一个字符在内存中要占2个字节,asic码则占一个字节,这肯定不一样
      

  5.   

    to bdmh
       那这个有什么解决方案吗,因为我读取和写入的文件类型是不一定的,有可能是图片,也有可能是视频文件,也有可能是文本文件
      

  6.   

    //用StreamReader 、StreamWriter 读写。。设置编码格式
    StreamReader sr=new StreamReader(filename,System.Text.Encoding.Default)StreamWriter sw=new StreamWriter(filename,false,System.Text.Encoding.Default)
      

  7.   

    StreamReader是只能操作文本文件的吧
      

  8.   

    我又调试了一下,如果不将文件分批量进行读取和写入就没有问题,但是如果把文件拆成多个byte就不行了,计算的字节我都有监视,没发现计算有问题啊,一开始是从0开始读取,然后每次最多读取200个字节,第二次就是从200的索引处进行读取了,这些都是依次存储到Queue<byte[]>泛型变量中的,写入到新文件里是从这个变量里依次取出数据进行写入
      

  9.   

    我超级靠,已经找到原因了,存储分批数据的临时缓存数组变量不是重新new出来的,所以一直重新创建的文件里的数据都是无效的
      

  10.   

    貌似不是你说的那种情况,实际上是每个汉字有2个字节,二有的符号或单词只有一个字节,你这样混合使用使错误的要做判断。你如果使用的是纯汉字文本相信只要byte中不是奇数那是会成功的
      

  11.   

    to yqb_6280180
      我代码已经修改成传对象过去处理的方式,分成文件对象实体和文件数据块实体,写入的时候把文件对象实体里的数据块实体分批传进去方法处理