C# 获取远程地址文件并转换为 FileInfo 对象
是的,C# 可以获取远程地址的文件并将其转换成 FileInfo 对象。以下是一个示例代码:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string remoteUrl = 'http://example.com/remote_file.txt';
FileInfo fileInfo = GetRemoteFileInfo(remoteUrl);
if (fileInfo != null)
{
Console.WriteLine('File Name: ' + fileInfo.Name);
Console.WriteLine('File Size: ' + fileInfo.Length);
Console.WriteLine('File Extension: ' + fileInfo.Extension);
// 其他FileInfo属性或方法的使用
}
else
{
Console.WriteLine('Failed to get remote file info.');
}
Console.ReadLine();
}
static FileInfo GetRemoteFileInfo(string remoteUrl)
{
try
{
Uri uri = new Uri(remoteUrl);
string fileName = Path.GetFileName(uri.LocalPath);
string tempFilePath = Path.GetTempFileName();
using (var webClient = new System.Net.WebClient())
{
webClient.DownloadFile(remoteUrl, tempFilePath);
}
return new FileInfo(tempFilePath);
}
catch (Exception ex)
{
Console.WriteLine('Error: ' + ex.Message);
return null;
}
}
}
上述代码中,GetRemoteFileInfo 方法接收一个远程地址的 URL,并使用 System.Net.WebClient 下载文件到临时文件路径 tempFilePath。然后,使用 FileInfo 类构造函数将临时文件路径转换成 FileInfo 对象,并返回该对象。
请注意,此示例中的远程地址应该是可公开访问的,如果需要身份验证或其他特殊处理,请根据实际需求进行修改。
原文地址: https://www.cveoy.top/t/topic/peYg 著作权归作者所有。请勿转载和采集!