我正在构建一个将.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();
我用Google搜索了这个,但我只能找到ASP示例。我似乎无法在这里找出我做错了什么。希望你们能帮助我。
谢谢!
答案 0 :(得分:3)
看起来,您正在尝试使用以下行列出ftp目录内容:
ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
尝试删除它,只留下这一行:
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;