c# - 将流传递给另一个函数时无法访问关闭的流
问题描述
我需要将流传递给另一个类中的几个函数,但它会引发错误
无法访问已关闭的流
这是代码:
第一种方法:
在这里,它使用 File.Open 方法打开一个文件,然后创建一个 memorystream 对象并将 FileStream 复制到 MemoryStream。然后将位置设置为 0(我将位置设置为 0,因为我在解决方案中,但没有帮助)。然后它创建一个类对象并通过将 MemoryStream 传递给它来DocxConvert
调用该方法。Converto
using (var stream = File.Open(tempPath2, FileMode.Open))
{
using(var ms = new MemoryStream())
{
stream.CopyTo(ms);
ms.Position = 0;
using (var docx = new DocxConvert())
{
return docx.Converto(ms);
}
}
}
DocxConvert 类:
它接受流,然后copyStream
通过传递接受的流来调用方法。
DocxConvert 类中的 copyStream 方法:它应该将接受的流复制到另一个称为_memoryStream
类属性的流。
public class DocxConvert
{
private MemoryStream _memoryStream = new MemoryStream();
public bool Converto(Stream stream)
{
try
{
copyStream(stream);
//more code
}
catch (IOException ex)
{
Debug.WriteLine(ex);
}
return true;
}
private void copyStream(Stream stream)
{
stream.CopyTo(_memoryStream); //here it throws the error
}
}
ps 我在发布之前在这里搜索了这个错误,但没有一个主题对我有帮助。
通过重新启动PC解决了,代码就可以了。
解决方案
我不知道你的问题。但是在下面的代码中没有例外
private void button1_Click(object sender, EventArgs e)
{
string tempPath2 = Application.StartupPath + "//" + "test.txt";
using (var stream = File.Open(tempPath2, FileMode.Open))
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
ms.Position = 0;
var docx = new DocxConvert();
var isok = docx.Converto(ms);
}
}
}
波纹管是定义的 _memorystream 在顶部定义的类
MemoryStream _memoryStream = new MemoryStream();
public bool Converto(Stream stream)
{
try
{
copyStream(stream);
//more code
}
catch (IOException ex)
{
// Debug.WriteLine(ex);
}
return true;
}
private void copyStream(Stream stream)
{
try
{
stream.CopyTo(_memoryStream);
}
catch (Exception)
{
}
}
推荐阅读
- c++ - 得到 ith,在 O(h) 中,h 是树的高度
- python - 使用 BeautifulSoup 查找 href 链接
- python - 根据单选按钮的一部分打印文本
- javascript - 如何在输入字段中添加必填项并在为空时更改消息错误?
- java - Docker 映像无法将我的 JSON 凭据密钥添加到我的 Google Cloud Natural Language 服务客户端
- amazon-s3 - 如何获得 s3 选择查询以返回单个行
- c - 如何正确释放 SDL_ttf 分配的资源?
- javascript - Exporting interface of redux store state
- php - 告诉文件的扩展名并回显某个值。(PHP/jQuery)
- laravel - 在 Laravel 中显示两个表中的数据