簡體   English   中英

在C#中使用FTP上傳包含編碼的文件

[英]Upload a file with encoding using FTP in C#

以下代碼適用於上傳文本文件,但無法上傳JPEG文件(不完全 - 文件名很好但圖像已損壞):

private void up(string sourceFile, string targetFile)
{
    try
    {
        string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
        string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
        string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];

        //string ftpURI = "";
        string filename = "ftp://" + ftpServerIP + "//" + targetFile;
        FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
        ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
        ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

        StreamReader stream = new StreamReader(sourceFile);
        Byte[] b = System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());
        stream.Close();

        ftpReq.ContentLength = b.Length;
        Stream s = ftpReq.GetRequestStream();
        s.Write(b, 0, b.Length);
        s.Close();

        System.Net.FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
        MessageBox.Show(ftpResp.StatusDescription);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

我有另一個可以上傳文件的解決方案:

private void Upload(string sourceFile, string targetFile)
{
    string ftpUserID;
    string ftpPassword;
    string ftpServerIP;
    ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
    ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
    ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
    FileInfo fileInf = new FileInfo(sourceFile);
    FtpWebRequest reqFTP;

    // Create FtpWebRequest object from the Uri provided
    reqFTP = (FtpWebRequest)(FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "//" + targetFile)));

    // Provide the WebPermission Credintials
    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

    // Bypass default lan settings
    reqFTP.Proxy = null;

    // By default KeepAlive is true, where the control connection is not closed
    // after a command is executed.
    reqFTP.KeepAlive = false;

    // Specify the command to be executed.
    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

    // Specify the data transfer type.
    reqFTP.UseBinary = true;

    // Notify the server about the size of the uploaded file
    reqFTP.ContentLength = fileInf.Length;

    // The buffer size is set to 2kb
    int buffLength = 2048;
    Byte[] buff;
    buff = new byte[buffLength];
    int contentLen;

    // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
    FileStream fs = fileInf.OpenRead();

    try
    {
        // Stream to which the file to be upload is written
        Stream strm = reqFTP.GetRequestStream();

        // Read from the file stream 2kb at a time
        long filesize = fs.Length;
        int i=0;
        contentLen = fs.Read(buff, 0, buffLength);

        // Till Stream content ends
        while (contentLen != 0)
        {
            Application.DoEvents();
            // Write Content from the file stream to the FTP Upload Stream
            strm.Write(buff, 0, contentLen);
            contentLen = fs.Read(buff, 0, buffLength);
            i = i + 1;
            //Double percentComp = (i * buffLength) * 100 / filesize;
            //ProgressBar1.Value = (int)percentComp;
        }

        // Close the file stream and the Request Stream
        strm.Close();
        fs.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Upload Error");
    }
}

但在這里我有相反的問題 - 圖片很好,但文件名已損壞。

我知道這是因為編碼,但我不知道如何使字節數組具有所需的編碼...

試試這個:

private static void up(string sourceFile, string targetFile)
{            
    try
    {
        string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
        string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
        string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
        ////string ftpURI = "";
        string filename = "ftp://" + ftpServerIP + "//" + targetFile; 
        FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
        ftpReq.UseBinary = true;
        ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
        ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

        byte[] b = File.ReadAllBytes(sourceFile);

        ftpReq.ContentLength = b.Length;
        using (Stream s = ftpReq.GetRequestStream())
        {
            s.Write(b, 0, b.Length);
        }

        FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

        if (ftpResp != null)
        {
            MessageBox.Show(ftpResp.StatusDescription);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

您應該使用Stream來讀取二進制文件,而不是StreamReader StreamReader僅用於讀取文本文件。

在您的第一個代碼示例中,啟用二進制傳輸: FtpWebRequest.UseBinary = true 否則它將轉換它認為是各種平台約定之間的文本行結尾(但實際上是圖像的一部分)。

你的第二個片段以正確的方式完成。 它使用FileStream,而不是StreamReader。 StreamReader僅適用於文本文件。

如果您遇到此問題: 使用HTTP時不支持請求的FTP命令

你需要在Null或Nothing中設置代理。

ftpReq.Proxy = null;

你可以看到這個博客。

http://mycodetrip.com/2008/10/29/fix-for-error-the-requested-ftp-command-is-not-supported-when-using-http-proxy_118/comment-page-1/#comment -2825

謝謝。

System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());

除非您的信息流的內容是文字,否則請勿這樣做。 將函數更改為接受布爾參數“binary”,如果設置了該標志,則使用后者的工作方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM