0

Rackspace .NET cloudifles API,GetObjectSaveToFile 方法获取文件并将其正确保存在指定位置,但是当使用 GetObject 方法时,如果我保存返回的内存流,则文件充满了一堆空值。

var cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
cloudFilesProvider.GetObjectSaveToFile(inIntStoreID.ToString(), @"C:\EnetData\Development\Sanbox\OpenStack\OpenStackConsole\testImages\", inStrFileName);

工作正常。但是当我尝试

System.IO.Stream outputStream = new System.IO.MemoryStream();
cloudFilesProvider.GetObject(inIntStoreID.ToString(), inStrFileName, outputStream);
FileStream file = new FileStream(strSrcFilePath, FileMode.Create, System.IO.FileAccess.Write);
byte[] bytes = new byte[outputStream.Length];
outputStream.Read(bytes, 0, (int)outputStream.Length);
file.Write(bytes, 0, bytes.Length);
file.Close();
outputStream.Close();

我得到一个包含一堆空值的文件。

4

2 回答 2

0

我认为您的问题的秘诀在于outputStream.Read- 的返回值可能返回 0。

我会尝试以下代码:

using (System.IO.Stream outputStream = new System.IO.MemoryStream())
{
    cloudFilesProvider.GetObject(inIntStoreID.ToString(), inStrFileName, outputStream);

    byte[] bytes = new byte[outputStream.Length];
    outputStream.Seek(0, SeekOrigin.Begin);

    int length = outputStream.Read(bytes, 0, bytes.Length);
    if (length < bytes.Length)
        Array.Resize(ref bytes, length);

    File.WriteAllBytes(strSrcFilePath, bytes);
}
于 2013-08-05T20:35:19.110 回答
0

我可以确认使用 IO.SeekOrigin.Begin 确实有效。所以我可以定义一个具有字节数组的类:-

 public class RackspaceStream
 {
    private  byte[] _bytes;

    public byte[] Bytes 
    {
        get { return _bytes; }
        set { _bytes = value; }
    }
    // other properties as needed
}

并使用与上面的帖子非常相似的代码将输出流中的字节分配给它。

    public RackspaceStream DownloadFileToByteStream(string containerName, string cloudObjectName)
    {
        RackspaceStream rsStream = new RackspaceStream();
        try
        {
            CloudFilesProvider cfp = GetCloudFilesProvider();

            using (System.IO.Stream outputStream = new System.IO.MemoryStream())
            {
                cfp.GetObject(containerName, cloudObjectName, outputStream);

                byte[] bytes = new byte[outputStream.Length];
                outputStream.Seek (0, System.IO.SeekOrigin.Begin);

                int length = outputStream.Read(bytes, 0, bytes.Length);
                if (length < bytes.Length)
                    Array.Resize(ref bytes, length);

                rsStream.Bytes = bytes; // assign the byte array to some other object which is declared as a byte array 

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);

        }
        return rsStream;
    } // DownloadFileSaveToDisk

然后返回的对象可以在其他地方使用.....

于 2016-05-21T07:39:29.583 回答