在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
相关产品推荐
相关产品推荐

