有一个需求,是要从一台服务器上下载文件到本地,然后自动把文件再上传到另一个服务器,我现在实现下载到本地了,可是如何只用后台代码直接上传呐,上传路径和下载路径都是固定的,一般的上传文件都是前台选取文件后台 HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;获取,可是现在没有这一部了,怎么搞
用这个模拟表单提交 HttpWebRequest
System.IO 命名空间下的FileStream 了解一下
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
//Create the file.
using (FileStream fs = File.Create(path))
{
AddText(fs, "This is some text");
AddText(fs, "This is some more text,");
AddText(fs, "\r\nand this is on a new line");
AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");
for (int i=1;i < 120;i++)
{
AddText(fs, Convert.ToChar(i).ToString());
}
}
//Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
private static void AddText(FileStream fs, string value)
{
byte[] info = new UTF8Encoding(true).GetBytes(value);
fs.Write(info, 0, info.Length);
}
}
https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.7.2
不太明白啊, HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;能不能手动给HttpFileCollection files添加文件啊?
我下载文件的时候已经获取到 Stream readStream = myRequest.GetResponse().GetResponseStream();这个文件的流,能不能直接用这个Stream进行上传操作啊?
@姚刘乐: FileStream 继承自 Stream
服务器上建个Ftp,下载上传都可以做