- 需求:库中存放文件服务器的文件绝对路径文件(
d:\abc\111\abc.pdf
),搭建的ftp会指向d:\abc
,故ftp:/192.1.1.12:21/111/abc.pdf
能取到文件。请用C#代码并base64格式返回到前端。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Data.Common;
using System.IO;
using System.Net;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var st = GetFileByPath();
Console.Write(st);
Console.ReadLine();
}
public static string GetFileByPath()
{
var filePath = "D:\\test\\1410\\412\\ab.pdf";
string oldDir = @"D:\test";
var dicFtp = JsonConvert.DeserializeObject<Dictionary<string, string>>(oldFtp);
var ftpPath = $"ftp://192.168.192.31:21/" + filePath.Replace(oldDir, "").Replace(@"\", @"/").TrimStart('/');
var str = DownloadFtp(ftpPath.Trim(), "", "");
WriteLog("111☆" + str);
return str;
}
private static string DownloadFtp(string ftpPath, string ftpUserID, string ftpPassword)
{
FtpWebRequest reqFTP;
try
{
MemoryStream mms = new MemoryStream();
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
mms.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
var res = Convert.ToBase64String(mms.ToArray());
ftpStream.Close();
mms.Close();
response.Close();
if (!string.IsNullOrWhiteSpace(res) && ftpPath.ToLower().EndsWith(".pdf"))
{
return "data:application/pdf;base64," + res;
}
else
{
return res;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void WriteLog(string content, string group = "方便归类")
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}: {1} {2}", group, content, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
string path = @"d:\";
Directory.CreateDirectory(path);//创建目录(存在,不重建不报错)
File.AppendAllText(path + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", "\r\n" + sb.ToString(), Encoding.UTF8);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2020-06-17 怎么自动把自己项目的dll文件copy到宿主bin文件夹?