如何将WebRequest流共享模式设置为share_read?

时间:2017-09-04 16:21:40

标签: c# webrequest

我使用here中的以下代码将大文件上传到ftp站点。 当文件上传到服务器时,我使用RDP转到服务器,无法打开它,因为它正由另一个进程使用。

我的问题是,我可以设置文件共享模式,以便在写入时可以读取文件吗?我想在上传文件时阅读它。

FileStream fs = null;
Stream rs = null;

try 
{
    string file = "D:\\RP-3160-driver.zip";
    string uploadFileName = new FileInfo(file).Name;
    string uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";
    fs = new FileStream(file, FileMode.Open, FileAccess.Read);

    string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
    FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
    requestObj.Method = WebRequestMethods.Ftp.UploadFile;
    requestObj.Credentials = new NetworkCredential("usernam", "password");
    rs = requestObj.GetRequestStream();

    byte[] buffer = new byte[8092];
    int read = 0;
    while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
    {
       rs.Write(buffer, 0, read);
    }
    rs.Flush();
}
catch (Exception e) 
{
    MessageBox.Show("File upload/transfer Failed.\r\nError Message:\r\n" + ex.Message, "Succeeded", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally 
{
    if (fs != null)
    {
        fs.Close();
        fs.Dispose();
    }

    if (rs != null)
    {
        rs.Close();
        rs.Dispose();
    }
}

1 个答案:

答案 0 :(得分:0)

尝试以下操作,我将FileShare.ReadWrite添加到FileStream:

string file = "D:\\RP-3160-driver.zip";
string uploadFileName = new FileInfo(file).Name;
string uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";

using (FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
    FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
    requestObj.Method = WebRequestMethods.Ftp.UploadFile;
    requestObj.Credentials = new NetworkCredential("usernam", "password");
    using (Stream rs = requestObj.GetRequestStream())
    {
        stream.CopyTo(rs);
    }
}