我想一个.txt文件上传到FTP服务器。 但我有一些问题。 我不断收到此错误: 远程服务器返回错误:(553)不允许的文件名。
这总是发生在这条线:
Stream writer = ftpReq.GetRequestStream();
我无法弄清楚的问题是什么。 我曾尝试与上传FileZilla的文件和工作正常。 我也试图文件目标网址从服务器复制并harcode到我的应用程序,但我仍然得到同样的错误。 是否有上传文件到FTP服务器的任何其他方式?
这是我的代码:
string localFilePath = @"\\fileprint\data\Groups\Operation\fileExports\folder\";
string archiveFilePath = @"\\fileprint\data\Groups\Operation\fileExports\folder\Archive\";
string logFilePath = @"C:\Users\lmy\Desktop\Logs";
string ftpServer = "ftp://my.server.no:21/home/pll332/tmp/";
private string logFileName = "" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();
string userName = "pll332";
string password = "password";
public Controller()
{
}
public void UploadFile()
{
try
{
string[] files = Directory.GetFiles(localFilePath);
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServer + fileName));
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.UsePassive = true;
ftpReq.UseBinary = true;
ftpReq.KeepAlive = true;
ftpReq.Credentials = new NetworkCredential(userName.Normalize(), password.Normalize());
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);
}
}
希望你们能帮助我。 谢谢!
编辑:我曾尝试这样的:
string fileName = Path.GetFileName(file);
UriBuilder uri = new UriBuilder();
uri.Scheme = "ftp";
uri.Host = "my.server.no";
uri.Port = 21;
uri.Path = "/home/username/tmp/";
uri.UserName = "username";
uri.Password = "password";
FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri.ToString() + fileName));
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.UsePassive = true;
ftpReq.UseBinary = true;
ftpReq.KeepAlive = true;
ftpReq.Credentials = new NetworkCredential(userName.Normalize(), password.Normalize());
这给了我同样的错误......