You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在UiPath Studio(VB.NET)中将邮件附件转为Base64字符串

将System.Net.Mail.Attachment转换为Base64字符串(VB.NET/UiPath)

完全可以通过ContentStream属性实现转换,下面是具体的实现思路和代码示例:

核心思路

System.Net.Mail.Attachment的ContentStream属性直接指向附件的内容数据流,我们只需要读取该流的字节数组,再通过Convert.ToBase64String()方法即可得到Base64字符串。

注意事项

  • 操作流前要确保流的Position属性重置为0,避免因流指针不在起始位置导致读取不完整。
  • 如果后续还需要使用原Attachment对象,操作完成后建议恢复流的原始位置,防止影响其他逻辑。

代码示例(UiPath Invoke Code活动中使用)

' 假设你已经获取到目标Attachment对象
Dim targetAttachment As System.Net.Mail.Attachment = YourAttachmentObject
Dim base64Result As String = String.Empty

' 保存流的原始位置
Dim originalStreamPosition As Long = targetAttachment.ContentStream.Position

Try
    ' 将流指针移到起始处
    targetAttachment.ContentStream.Position = 0
    
    ' 读取流中的所有字节
    Using binaryReader As New BinaryReader(targetAttachment.ContentStream)
        Dim attachmentBytes() As Byte = binaryReader.ReadBytes(CInt(targetAttachment.ContentStream.Length))
        ' 转换为Base64字符串
        base64Result = Convert.ToBase64String(attachmentBytes)
    End Using
Finally
    ' 恢复流的原始位置
    targetAttachment.ContentStream.Position = originalStreamPosition
End Try

' 输出结果(可根据UiPath需求赋值给变量)
Console.WriteLine(base64Result)

备选方案(处理特殊流场景)

如果遇到ContentStream无法直接读取的情况(极少出现),可以先将流复制到MemoryStream再处理:

Dim targetAttachment As System.Net.Mail.Attachment = YourAttachmentObject
Dim base64Result As String = String.Empty

Using tempStream As New MemoryStream()
    ' 将ContentStream复制到临时内存流
    targetAttachment.ContentStream.CopyTo(tempStream)
    ' 重置内存流指针
    tempStream.Position = 0
    ' 转换为Base64
    base64Result = Convert.ToBase64String(tempStream.ToArray())
End Using

内容的提问来源于stack exchange,提问作者caseodilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:50:21