簡體   English   中英

將文本文件上傳到FTP服務器C#時出錯

[英]Error while uploading a text file to FTP server C#

我正在構建一個簡單的應用程序,該程序將.txt文件上傳到FTP服務器。 我之前已經做過這件事,並且我使用的代碼與其他應用程序所用的代碼相同。

這是我的代碼:

string localFilePath = @"\\fileprint\data\Groups\Operation\fileExports\dls\";
string archiveFilePath = @"\\fileprint\data\Groups\Operation\fileExports\dls\Archive\";
string logFilePath = @"C:\Users\lmy\Desktop\Logs";
string ftpServer = "ftp://server:21/home/out2233/tmp";
private string logFileName = "" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();

public void UploadFile()
{
    try
    {
        string[] files = Directory.GetFiles(localFilePath);
        foreach (string file in files)
        {
            string fileName = Path.GetFileName(file);
            string modified = file.Remove(60, 6);
            string modifiedFile = Path.GetFileName(modified);
            FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServer + modifiedFile));
            ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
            ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            ftpReq.UsePassive = true;
            ftpReq.UseBinary = true;
            ftpReq.KeepAlive = true;
            ftpReq.Credentials = new NetworkCredential("out2233", "password");
            ftpReq.EnableSsl = true;

            FileInfo fileInfo = new FileInfo(localFilePath + @"\" + fileName);
            FileStream fileStream = fileInfo.OpenRead();

            byte[] fileContent = new byte[fileInfo.Length];
            fileStream.Read(fileContent, 0, Convert.ToInt32(fileInfo.Length));

            Stream writer = ftpReq.GetRequestStream();
            writer.Write(fileContent, 0, fileContent.Length);
            fileStream.Close();
            writer.Close();
            FtpWebResponse response = (FtpWebResponse)ftpReq.GetResponse();

            AppendLogFile(response, "Uploaded Files: ", fileName);
            MoveToArchive(file, archiveFilePath + fileName);
        }

    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);
    }
}

但它得到以下錯誤: exception = {“無法發送具有此動詞類型的內容主體。”}

當代碼到達此行時:

Stream writer = ftpReq.GetRequestStream();

我用谷歌搜索,但是我只能找到ASP示例。 我似乎無法找出我在這里做錯了什么。 希望你們能幫助我。

謝謝!

看起來,您正在嘗試使用以下行列出ftp目錄內容:

ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 

http://msdn.microsoft.com/zh-cn/library/system.net.webrequestmethods.ftp.listdirectorydetails%28v=vs.110%29.aspx

嘗試將其刪除,僅保留以下行:

ftpReq.Method = WebRequestMethods.Ftp.UploadFile; 

http://msdn.microsoft.com/zh-cn/library/system.net.webrequestmethods.ftp.uploadfile%28v=vs.110%29.aspx

暫無
暫無

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

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