c# - 无法将类型 'System.Net.FileWebRequest' 的对象强制转换为类型 'System.Net.HttpWebRequest'

标签 c# .net c#-4.0 c#-3.0

我在尝试上传到 FTP 时遇到上述错误。但是当我尝试从本地计算机运行此代码时,它出现错误。好心提醒。

这是我的代码:

 static void Main(string[] args)
    {

        var yourListOfFilePaths = Directory.GetFiles(filepath);

        using (ZipFile zip = new ZipFile())
        {
            foreach (string filePath in yourListOfFilePaths)
            {
                zip.AddFile(filePath);    // FILE PATH LOCATION / WHICH FOLDER FILES YOU WANTED TO ZIP
                zip.Password = "abc1234"; // CHANGE YOUR PASSWORD HERE 
            }
            zip.Save(ZipPath + "\\Batch_" + DateTime.Now.ToString("ddMMyy") + ".zip");

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("http://www.bitrix24.com/" + "\\Batch_" + DateTime.Now.ToString("ddMMyy") + ".zip");
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fef5edf0f1fad4f6fde0e6fdeca6a0baf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a>", "abc123");

            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader(ZipPath + "\\Batch_" + DateTime.Now.ToString("ddMMyy") + ".zip");
            byte[] fileContents = File.ReadAllBytes("filepath");
            sourceStream.Close();
            request.ContentLength = fileContents.Length;
            request.KeepAlive = false;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();

        }
    }

最佳答案

这个:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("http://www.bitrix24.com/"
                              + "\\Batch_" + DateTime.Now.ToString("ddMMyy") + ".zip");

是你的问题吗?您发送的地址以“http”而不是“ftp”开头。

更改您的网址:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.bitrix24.com/" + 
                                "\\Batch_" + DateTime.Now.ToString("ddMMyy") + ".zip");

关于c# - 无法将类型 'System.Net.FileWebRequest' 的对象强制转换为类型 'System.Net.HttpWebRequest',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28084108/

相关文章:

c# - 如何使用 Aspose.Word 获取 word 文档中所有未加载的图像

asp.net - 我应该多久打开/关闭一次 Booksleeve 连接?

c# - Entity Framework 4 : Table per Type inheritance problem on insert

c# - 解析未知 JSON 对象以获取特定值

c# - 7z格式压缩

.net - DataContract Serializer 数组节点名称 'd3p1'

c# - 当进行非常大的插入时,不参数化 MySQL 查询而是使用方法 MySqlHelper.EscapeString(string) 是否安全?

c#-4.0 - 在 VS 2010 中向 Windows 服务添加 System.Threading.Timer

c#-4.0 - Redis 将 HashSet 获取到所需的类型而不适用于可空类型

C# 如何检查对象是否可为空