同时访问Stream

时间:2011-08-04 15:32:18

标签: c# silverlight windows-phone-7

我试图多次重复使用相同的Stream。一个用于调整图像大小,另一个用于上传图像。虽然它确实可以调整图像的大小,但它似乎锁定了上传文件的其他方法。我曾尝试使用Stream.CopyTo(MemoryStream)复制Stream,然后使用它进行上传,但它仍然没有区别。

我正在使用PhotoChooserTask打开一个Stream。然后我将Stream传递给ImageThumbnail方法,该方法创建图像的缩略图,然后将其保存到IsolatedStorage,如下所示:

    public static void SaveThumbnail(Stream imageStream, string fileName, double imageMaxHeight, double imageMaxWidth)
    {
        var bitmapImage = new BitmapImage();
        bitmapImage.SetSource(imageStream);
        var resizedImage = new WriteableBitmap(bitmapImage);

        using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            double scaleX = 1;
            using (var fileStream = isolatedStorage.CreateFile(fileName))
            {
                //do stuff for resizing here...
                resizedImage.SaveJpeg(fileStream, newWidth1, newHeight1, 0, 100);
            }
        }
    }

与此同时,我正在重复使用PhotoChooserTask中的相同Stream来上传图像。 EItherway,它似乎是将彼此锁定,并且没有错误被抛出。

任何提示?

2 个答案:

答案 0 :(得分:4)

您需要copy the stream into a byte array,因为流在​​使用过程中会发生变化而无法克隆。

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    while (true)
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
}

答案 1 :(得分:1)

复制到MemoryStream应该可以解决问题。要重用内存流,您需要通过将Position属性设置回0来将位置重置回头。

相关问题