1

我有一个客户端服务器应用程序,它通过 wcf 以传输模式流进行通信。当客户端尝试一次下载文件时,它可以工作,但是当客户端尝试两次下载整个文件时,下载的文件已损坏并且无法打开。

客户代码:

public void DownloadPart(Part Part) //Part: Part.From,Part.To -> possitions in the stream from where to begin and when to end reading
                {
                    int ReadUntilNow = 0;
                    int ReadNow = 0;
                    byte[] Array= new byte[15000];
                    long NeedToDownload = Part.To - Part.From;
                    using (FileStream MyFile = new FileStream(Path_To_Save_The_File, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    {
                        MyFile.Position = Part.From;
                        while (ReadUntilNow < NeedToDownload)
                        {
                            ReadNow = this.SeederInterface.GetBytes(TorrentID, Part.From + ReadUntilNow, ref Array);
                            ReadUntilNow += ReadNow;
                            MyFile.Write(Array, 0, ReadNow);
                        }
                    }
                }

服务器代码:

public int GetBytes(int TorrentID, int Position, ref byte[] Array)
        {
            FileStream File = new FileStream(FilePatch, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            File.Position = Position;
            return File.Read(Array, 0, Array.Length);
        }

我真的很绝望,不知道是什么问题。

4

1 回答 1

1

This is going to overwrite any existing output file. You have:

using (FileStream MyFile = new FileStream(Path_To_Save_The_File, 
    FileMode.Create, FileAccess.Write, FileShare.ReadWrite))

That will create a new file, or overwrite the existing file.

In the next line, you have:

MyFile.Position = Part.From

That will extend the file, and the first part of the file will contain garbage--whatever was on the disk in that space.

I think what you want is to change the Mode in your open call to FileMode.OpenOrCreate, as in:

using (FileStream MyFile = new FileStream(Path_To_Save_The_File, 
    FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))

That will open the file if it already exists. Otherwise it will create a new file.

You'll probably want to determine if you're downloading the first part of the file (i.e. a new file), and delete any existing file if so. Otherwise, your code could overwrite the first part of the new file, but not truncate.

于 2013-04-16T16:30:52.787 回答