如何从fileupload控件设置Filestream?

时间:2011-10-27 20:25:55

标签: asp.net visual-studio-2010 c#-4.0 asp.net-4.0

这是我的代码,我似乎无法将FileUploadCotrol中的文件存入FILESTREAM。

 // The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();

try
{
    // Stream to which the file to be upload is written
    Stream strm = reqFTP.GetRequestStream();

    // Read from the file stream 2kb at a time
    contentLen = fs.Read(buff, 0, buffLength);

    // Till Stream content ends
    while (contentLen != 0)
    {
        // Write Content from the file stream to the FTP Upload Stream
        strm.Write(buff, 0, contentLen);
        contentLen = fs.Read(buff, 0, buffLength);
    }

    // Close the file stream and the Request Stream
    strm.Close();
    fs.Close();
}

似乎我应该使用Fileupload控件来从我的网站执行此操作,但它接口很奇怪控件创建流而不是文件流。是的我正在FTP文件。

1 个答案:

答案 0 :(得分:0)

以下是一种示例方法,它将我们定位的两种类型FileInfoFtpWebRequest作为参数并在它们之间传输数据。我相信这会奏效。

    void UploadFileToFtp(FileInfo file, FtpWebRequest req)
    {
        int buffLength = 2048;

        using (var reader = new BinaryReader(file.OpenRead()))
        {
            using (var writer = new BinaryWriter(req.GetRequestStream()))
            {
                while (reader.PeekChar() > 0) writer.Write(reader.ReadBytes(buffLength));
            }
        }
    }

希望这有帮助!