2 years ago

#64252

test-img

midoriyakuzan

.NET 6 WebRequest Alternative for FTP

I'm migrating my FTPSender project to .net 6. I was using FTPClient as below

public bool UploadFile(string sourceFile,string destinationUrl)
        {
             try
            {
                if (ftpType == FtpTypes.SSH)
                {

                    Sftp sftp = new Sftp(hostAdress, userName, password);
                    sftp.Connect(22);
                    sftp.Put(sourceFile, destinationUrl);
                    sftp.Close();

                    if (destinationUrl.Contains("#"))
                    {
                        var sshExec = new SshExec(hostAdress, userName, password);
                        sshExec.Connect();
                        var err = string.Empty;
                        var outx = string.Empty;
                        sshExec.RunCommand("mv " + destinationUrl + " " + destinationUrl.Replace("#", ""), ref outx, ref err);
                        sshExec.Close();
                    }

                }
                else
                {
                    FileInfo file = new FileInfo(sourceFile);
                    FtpWebRequest reqFTP;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(hostAdress + destinationUrl));
                    reqFTP.Credentials = new NetworkCredential(userName, password);
                    reqFTP.KeepAlive = false;
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                    reqFTP.UseBinary = true;
                    reqFTP.ContentLength = file.Length;
                    int buffLength = 2048;
                    byte[] buff = new byte[buffLength];
                    int contentLen;
                    FileStream fs = file.OpenRead();
                    Stream strm = reqFTP.GetRequestStream();
                    contentLen = fs.Read(buff, 0, buffLength);
                    while (contentLen != 0)
                    {
                        strm.Write(buff, 0, contentLen);
                        contentLen = fs.Read(buff, 0, buffLength);
                    }
                    strm.Close();
                    fs.Close();
                }
            }
            catch(Exception ex)
            {
                return false;

            }

            return true;
            
        }

I copied the exact copy on .net 6. But it gives error SYSLIB0014.

WebRequest, HttpWebRequest, ServicePoint, WebClient are obsolete.Use HttpClient instead.

When I enter the HttpClient page another warning is

For FTP, since HttpClient doesn't support it, we recommend using a third-party library.

Is WebRequest still available or What should i use? How to implement it?

c#

.net

asp.net-core

ftp

0 Answers

Your Answer

Accepted video resources