2013-08-05 15 views
0

Rackspace的.NET cloudifles API,該GetObjectSaveToFile方法獲取文件,並妥善保存在指定的位置,但使用GetObject方法時,如果我救回來的MemoryStream該文件充滿了大量的空值。使用GetObject的,返回的內存流爲空,而GetObjectSaveToFile返回正確的文件

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(); 

我得到一個文件,它有一堆的空值。

回答

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); 
} 
+0

燁一遍工作謝謝:) – gopstar

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 

那麼返回的對象可以用在別處.....

相關問題