以下是将txt文件从某个位置复制到ftp路径的代码段:
WebRequest WRequest = WebRequest.Create(FtpPath + OriginalfileName);
WRequest.Method = WebRequestMethods.Ftp.UploadFile;
WRequest.Credentials = new NetworkCredential("myusername", "FtpPassword");
FileStream stream = File.OpenRead(OriginalFilePath);
byte[] buffer = new byte[stream.Length];
Stream RStream = WRequest.GetRequestStream();
RStream.Write(buffer, 0, buffer.Length);
RStream.Close();
但是ftp目标处的复制文件始终为空。为什么呢?
答案 0 :(得分:4)
您没有使用文件内容填充缓冲区。您只需在以下代码行中设置长度:
byte[] buffer = new byte[stream.Length];
你也没有在其他地方填写文件的内容,所以你只是将空数据发送到FTP服务器。字节可能有一定的长度,但它都是空字节。
答案 1 :(得分:2)
作为一个简单的解决方案,您可以使用WebClient类
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile(uriString,fileName);
答案 2 :(得分:1)
您可以在写入字节时应用相同类型的逻辑,除非在我的情况下我传入了初始大小
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
答案 3 :(得分:0)
这应该有效:
WebRequest WRequest = WebRequest.Create(FtpPath + OriginalfileName);
WRequest.Method = WebRequestMethods.Ftp.UploadFile;
WRequest.Credentials = new NetworkCredential("myusername", "FtpPassword");
using (FileStream stream = File.OpenRead(OriginalFilePath)) {
using (Stream RStream = WRequest.GetRequestStream()) {
stream.CopyTo(RStream);
}
}
答案 4 :(得分:0)
这是在asp.net core 2.1中使用IFormFile上传文件的解决方案
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("*******/site/wwwroot/wwwroot/images/" + TempFileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.KeepAlive = false;
request.Method = "STOR";
request.Credentials = new NetworkCredential("***", "****");
// Copy the contents of the file to the request stream.
byte[] fileContents = null;
if (vehicle.FileUpload.Length > 0)
{
using (var ms = new MemoryStream())
{
await vehicle.FileUpload.CopyToAsync(ms);
var fileBytes = ms.ToArray();
fileContents = fileBytes;
}
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
这是文件的视图模型
public class VehicleSeriesViewModel
{
public Guid VehicleBadgeId { get; set; }
public Guid VehicleSeriesId { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public IFormFile FileUpload { get; set; }
public string PictureUrl { get; set; }
}