Skip to main content
 首页 » 编程设计

c#之使用 webClient 保存网络驱动器照片

2024年02月05日27mq0036

嘿,我有以下 VB.net 代码,我需要将其转换为 C#:

 Dim tClient As WebClient = New WebClient 
 Dim imgLink As String = "\\the\path\photos\" + userID + ".jpg" 
 Dim tImage As Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData(imgLink))) 
 
 Dim mImage As String = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg) 

这在 VB 中工作得很好,但是当我尝试将它转换为 C# 时:

WebClient tClient = new WebClient(); 
string mImage = @"\\the\path\photos\" + userID + ".jpg"; 
Bitmap tImage = Bitmap.FromStream[new MemoryStream[tClient.DownloadData(mImage)]]; 
 
mImage = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg); 

它在 tClient.DownloadData(imagePath) 上有一个错误说:

Error 7 Cannot implicitly convert type 'byte[]' to 'int'

在 C# 中定义它的正确方法是什么?

请您参考如下方法:

有几个问题:

  • 您在 Bitmap.FromStream 和 MemoryStream 构造函数中混淆了数组运算符括号 [ 和函数调用 ( 括号
  • 您一次下载整个文件,只是为了将其加载到流中 - 这违背了流式传输的目的
  • Bitmap.FromStream 实际上来自它的父类(super class) Image,并返回一个 Image(您不能保证该文件将是实际的位图,而不是其他格式 - 如果您确定它,则必须强制转换它到位图)

试试这个:

WebClient tClient = new WebClient(); 
string mImage = @"\\the\path\photos\" + userID + ".jpg"; 
Bitmap tImage = (Bitmap)Bitmap.FromStream(tClient.OpenRead(mImage)); 
 
mImage = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg); 

WebClient.OpenRead 返回一个流,您可以直接传递它来构建图像(无需将所有数据拉到字节数组)