无法访问封闭的Stream

时间:2011-11-01 16:53:08

标签: c# stream thread-safety networkstream

我使用Taglib更改内存中的某些标记,我尝试做的是使用流读取文件,将流复制到memoryStream进行一些更改,即(file.Tag.Comment =“我的新评论”),然后使用最新的流进行下载。这是我的代码:

Stream fileStream = null;

// Buffer To Read 10K Bytes In Chunk:
Byte[] Buffer = new Byte[10000];

// Length Of The File:
int Length;

// Identify The File To Download Including Its Path.
System.IO.FileInfo fileInfo = new System.IO.FileInfo(@"c:\123.mp3");
string fn = fileInfo.FullName;

try
{
    fileStream = new System.IO.FileStream(fn, System.IO.FileMode.Open, System.IO.FileAccess.Read);

// Copy the Stream to a MemoryStream
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(fileStream.Length);
fileStream.Read(storeStream.GetBuffer(), 0, (int)fileStream.Length);

var streamFileAbstraction = new StreamFileAbstraction(fileStream, fn, storeStream);

using (var file = TagLib.File.Create(streamFileAbstraction))
{
    file.Tag.Comment = "my New comments";
    file.Save();
}

我不断收到“无法访问已关闭的流”。在

file.Save();

我的StreamFileAbstraction看起来像这样:

public class StreamFileAbstraction : TagLib.File.IFileAbstraction
{
    private string name;
    private Stream thefile;
    private MemoryStream memStream;

    public StreamFileAbstraction(Stream file, String filename, MemoryStream ms)
    {
        name = filename;
        thefile = file;
        memStream = ms;
    }

    public void CloseStream(Stream stream)
    {
        stream.Close();
    }

    public string Name
    {
        get { return name; }
    }

    public Stream ReadStream
    {
        get { return memStream; }
    }

    public Stream WriteStream
    {
        get 
        {
            byte[] buffer = ReadFully(memStream); //.ReadAllBytes(memStream.Length.ToString());
            MemoryStream ms2 = new MemoryStream(); 
            //return new MemoryStream(buffer, 0, buffer.Length);
            //return new FileStream(Name, FileMode.Open, System.IO.FileAccess.Write); 
            //return new MemoryStream(buffer, true /*writable*/); 
            return new MemoryStream(); 
        }
    }

    public Stream Thefile
    {
        get { return thefile; }
    }

    public byte[] ReadFully(Stream stream)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                memoryStream.Write(buffer, 0, bytesRead);
            }
            return memoryStream.ToArray();
        }
    }

}

对于WriteStream / ReadStream我不确定我应该放在那里的代码,所以它可能是错的?

非常希望收到你的来信。

感谢

0 个答案:

没有答案