سؤال

يهدف الرمز التالي إلى استرداد ملف عبر FTP. ومع ذلك ، أحصل على خطأ في ذلك.

serverPath = "ftp://x.x.x.x/tmp/myfile.txt";

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;

request.Method = WebRequestMethods.Ftp.DownloadFile;                
request.Credentials = new NetworkCredential(username, password);

// Read the file from the server & write to destination                
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))            
using (StreamWriter destination = new StreamWriter(destinationFile))
{
    destination.Write(reader.ReadToEnd());
    destination.Flush();
}

الخطأ هو:

أعاد الخادم البعيد خطأ: (550) ملف غير متوفر (على سبيل المثال ، لم يتم العثور على الملف ، لا وصول)

من المؤكد أن الملف موجود على الجهاز البعيد وأتمكن من أداء هذه FTP يدويًا (أي لدي أذونات). هل يمكن لأي شخص أن يخبرني لماذا قد أحصل على هذا الخطأ؟

هل كانت مفيدة؟

المحلول

هذه الفقرة من fptwebrequest مرجع فئة قد تكون ذات أهمية بالنسبة لك:

قد يكون URI نسبيًا أو مطلقًا. إذا كان URI من النموذج "ftp://contoso.com/٪2FPath"(٪ 2F هو /" هرب " /") ، فإن URI مطلقة ، والدليل الحالي هو /مسار. إذا كان URI من النموذج ".ftp://contoso.com/path"، أولاً ، يقوم .NET Framework بتسجيل الدخول إلى خادم FTP (باستخدام اسم المستخدم وكلمة المرور المعينة بواسطة خاصية بيانات الاعتماد) ، ثم يتم تعيين الدليل الحالي على /PATH.

نصائح أخرى

أعلم أن هذا منشور قديم ولكني أضيف هنا للرجوع إليه في المستقبل. هذا هو الحل الذي وجدته:

    private void DownloadFileFTP()
    {
        string inputfilepath = @"C:\Temp\FileName.exe";
        string ftphost = "xxx.xx.x.xxx";
        string ftpfilepath = "/Updater/Dir1/FileName.exe";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
            byte[] fileData = request.DownloadData(ftpfullpath);

            using (FileStream file = File.Create(inputfilepath))
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
        }
    }

تم تحديثه بناءً على اقتراح ممتاز من إيليا كوجان

أسهل طريقة

الطريقة الأكثر تافهة لتنزيل ملف ثنائي من خادم FTP باستخدام .NET Framework تستخدم WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

خيارات متقدمة

يستخدم FtpWebRequest, ، فقط إذا كنت بحاجة إلى تحكم أكبر ، ذلك WebClient لا يقدم (مثل تشفير TLS/SSL, ، مراقبة التقدم الخ). الطريقة السهلة هي مجرد نسخ دفق استجابة FTP إلى FileStream استخدام Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

رصد التقدم

إذا كنت بحاجة إلى مراقبة تقدم التنزيل ، فيجب عليك نسخ المحتويات عن طريق القطع بنفسك:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

للتقدم في واجهة المستخدم الرسومية (WinForms ProgressBar)، نرى:
FTPWebRequest FTP تنزيل مع ProgressBar


مجلد تنزيل

إذا كنت ترغب في تنزيل جميع الملفات من مجلد بعيد ، انظر
C# قم بتنزيل جميع الملفات والمدافع الفرعي من خلال FTP.

كان لي نفس القضية!

كان حلي هو إدراج public_html المجلد في عنوان URL تحميل.

موقع الملف الحقيقي على الخادم:

myhost.com/public_html/myimages/image.png

عنوان URL على الويب:

www.myhost.com/myimages/image.png

    private static DataTable ReadFTP_CSV()
    {
        String ftpserver = "ftp://servername/ImportData/xxxx.csv";
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();

        // use the stream to read file from FTP 
        StreamReader sr = new StreamReader(responseStream);
        DataTable dt_csvFile = new DataTable();

        #region Code
        //Add Code Here To Loop txt or CSV file
        #endregion

        return dt_csvFile;

    }

آمل أن تساعدك.

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

بعد ذلك يمكنك استخدام السطر أدناه لتجنب الخطأ .. (تم رفض الوصول وما إلى ذلك)

request.Proxy = null;
   public void download(string remoteFile, string localFile)
    {
       private string host = "yourhost";
       private string user = "username";
       private string pass = "passwd";
       private FtpWebRequest ftpRequest = null;
       private FtpWebResponse ftpResponse = null;
       private Stream ftpStream = null;
       private int bufferSize = 2048;

        try
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            ftpStream = ftpResponse.GetResponseStream();

            FileStream localFileStream = new FileStream(localFile, FileMode.Create);

            byte[] byteBuffer = new byte[bufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);

            try
            {
                while (bytesRead > 0)
                {
                    localFileStream.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                }
            }

            catch (Exception) {  }

            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }

        catch (Exception) {  }
        return;
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top