如何在C#中将图像转换为base64字符串?
例如,我有图像的路径,C:/image/1.gif并希望data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..返回.
我正在尝试将 sql server 中存储的内容作为 varbinary(max) 流式传输到客户端。我能够使其工作,但是连接将保持打开状态,直到垃圾收集。如果我在返回结果之前处置连接、读取器或蒸汽,则会导致对象处置错误。
我希望避免将数据复制到内存中(因为它可能很大),同时在完成后正确处理对象。实现这两个目标的最佳方法是什么?
如果相关的话,我正在使用 .NET Core 2.0。
更新:这不是其他人的重复(How do I dispose my filestream when Implementing a file download in ASP.NET?),因为我不是问如何处置流,而是问如何处置相关的连接对象。我的问题更多是关于确保连接对象被处置的正确方法
下面的代码成功返回结果,但留下未释放的连接:
public async Task<IActionResult> DownloadFile(Guid FileId)
{
var connection = new SqlConnection(DatabaseService.ConnectionString);
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "select FileName, FileContent from Files where FileId=@FileId";
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("@FileId", FileId);
var reader = await command.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess | System.Data.CommandBehavior.SingleRow);
if (!await reader.ReadAsync())
return NotFound();
var attachmentName = Convert.ToString(reader[0]);
var stream = reader.GetStream(1);
var response …Run Code Online (Sandbox Code Playgroud)