Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.HttpWebRequest'

荒凉一梦 提交于 2021-01-28 05:05:57

问题


I'm getting the above error when trying to test on upload to FTP. But when I'm trying run this code from my local machine, it is giving error. Kindly advise.

Here my code below :

 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("jayden@bitrix24.com", "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();

        }
    }

回答1:


This:

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

Is your problem. You're sending an address which starts with "http" instead of "ftp.

Change your URL:

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


来源:https://stackoverflow.com/questions/28084108/unable-to-cast-object-of-type-system-net-filewebrequest-to-type-system-net-ht

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!