【问题标题】:Streaming a file in parts - not working分部分流式传输文件 - 不工作
【发布时间】:2013-04-16 15:12:30
【问题描述】:

我有一个客户端服务器应用程序,它通过 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);
        }

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

【问题讨论】:

    标签: c# wcf stream


    【解决方案1】:

    这将覆盖任何现有的输出文件。你有:

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

    这将创建一个新文件,或覆盖现有文件。

    在下一行,你有:

    MyFile.Position = Part.From
    

    这将扩展文件,并且文件的第一部分将包含垃圾——无论该空间中磁盘上的内容。

    我认为您想要的是将公开呼叫中的Mode 更改为FileMode.OpenOrCreate,如下所示:

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

    如果文件已经存在,它将打开它。否则它将创建一个新文件。

    您可能需要确定是否正在下载文件的第一部分(即新文件),如果是,则删除任何现有文件。否则,您的代码可能会覆盖新文件的第一部分,但不会截断。

    【讨论】:

    • 哇,那是我的错误……我不敢相信。非常感谢您的参与!我还是不敢相信我没看到!谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2018-04-11
    • 2015-06-28
    • 1970-01-01
    • 2010-09-24
    • 2016-05-30
    • 2015-08-24
    相关资源
    最近更新 更多