簡體   English   中英

使用 C# 從 Firebase 下載文件

[英]Download a file from Firebase using C#

提前致謝
我正在嘗試使用 C# 從 firebase 下載文件,特別是 PDF 文件
它不斷拋出異常: “遠程服務器返回錯誤:(403)禁止訪問。”
我嘗試將鏈接轉換為 Uri,我嘗試將其硬編碼為“gs://xxxxxxx.appspot.com/PDF/MyPDF.pdf”

注意添加的兩行沒有幫助

我究竟做錯了什么

這是代碼:

        // ----------------------------------------------------------------------------

        private async Task download( string folder, string fileName )
        {
            FirebaseStorage storage = new FirebaseStorage( Bucket,
                 new FirebaseStorageOptions
                 {
                     AuthTokenAsyncFactory = () => Task.FromResult(
                         fireBaseAuthLink.FirebaseToken ),
                     ThrowOnCancel = true,
                 } );

            var fileRef = storage.Child( folder ).Child( fileName );
            string link = "";
            try
            {
                link = await fileRef.GetDownloadUrlAsync();
                var info = await fileRef.GetMetaDataAsync();
                processDownload( fileName, link, (int)info.Size );
            }
            catch( Exception we )
            {
                MessageBox.Show( we.Message );
            }
        }

        // ----------------------------------------------------------------------------

        private void processDownload( string finalFileName, string link, int size )
        {
            try
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create( link );
                httpRequest.Method = "GET";

                // These two lines added to try to get it to work ----------------
                httpRequest.UseDefaultCredentials = true;
                httpRequest.Proxy.Credentials =
                    System.Net.CredentialCache.DefaultCredentials;
                // ---------------------------------------------------------------

                httpRequest.ContentType = "application/pdf; encoding='utf-8'";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                Stream httpResponseStream = httpResponse.GetResponseStream();

                // Define buffer and buffer size
                byte[] buffer = new byte[size];
                int bytesRead = 0;

                // Read from response and write to file
                FileStream fileStream = File.Create( finalFileName );
                while( ( bytesRead = httpResponseStream.Read( buffer, 0, size ) ) != 0 )
                {
                    fileStream.Write( buffer, 0, bytesRead );
                }
            }
            catch( WebException we )
            {
                MessageBox.Show( we.Message ); 
            }
        }

而 firebase 規則是

rules_version = '2';
service firebase.storage {
    match /b/{bucket}/o {
        match /PDF/{allPaths=**} {
           allow get;
           allow read;
           allow write;
  }
}

對於那些實際上不想下載它的人來說,這是一個替代答案
只需替換該行:

processDownload( fileName, link, (int)info.Size );

System.Diagnostics.Process.Start( link );

這將在您的瀏覽器中打開 PDF

好的,經過多次挫折和搜索我成功了
C# 專家,請告訴我我不需要什么,我是android開發人員:)

這是答案

        // ----------------------------------------------------------------------------

        private async Task download( string folder, string fileName )
        {
            FirebaseStorage storage = new FirebaseStorage( Bucket,
                 new FirebaseStorageOptions
                 {
                     AuthTokenAsyncFactory = () => Task.FromResult(
                         fireBaseAuthLink.FirebaseToken ),
                     ThrowOnCancel = true,
                 } );

            var fileRef = storage.Child( folder ).Child( fileName );
            string link = "";
            try
            {
                link = await fileRef.GetDownloadUrlAsync();
                var info = await fileRef.GetMetaDataAsync();
                processDownload( fileName, link, (int)info.Size );
            }
            catch( Exception we )
            {
                MessageBox.Show( we.Message );
            }
        }

        // ----------------------------------------------------------------------------

        private void processDownload( string finalFileName, string link, int size )
        {
            try
            {
                HttpWebRequest httpWebRequest =
                    (HttpWebRequest)WebRequest.Create( link );

                HttpWebResponse httpResponse = 
                    (HttpWebResponse)httpWebRequest.GetResponse();
                
                HttpContext.Current = new HttpContext(
                    new HttpRequest( link, link, "" ),
                    new HttpResponse( new StringWriter() )
                    );
                
                HttpResponse response = HttpContext.Current.Response;
                response.ClearContent();
                response.Clear();
                response.ClearHeaders();
                response.Buffer = true;
                response.ContentType = "application/pdf";
                response.AddHeader( "Content-Disposition",
                    "attachment; filename=\"" + finalFileName + "\"" );

                byte[] buffer = new byte[size];
                int bytesRead = 0;

                string userProfile = System.Environment.GetEnvironmentVariable( "USERPROFILE" );
                string downloadsFolder = userProfile + "/Downloads/";
                FileStream fileStream = File.Create( downloadsFolder + finalFileName );
                Stream httpResponseStream = httpResponse.GetResponseStream();
                while( ( bytesRead = httpResponseStream.Read( buffer, 0, size ) ) != 0 )
                {
                    fileStream.Write( buffer, 0, bytesRead );
                }
                
                fileStream.Flush();
                fileStream.Close();
                response.Flush();
                response.End();
                httpResponse.Close();
            }
            catch( WebException we )
            {
                MessageBox.Show( we.Message );
            }
        }
    }

感謝所有幫助過的人

好吧,真是個啟示,我在 Google Cloud Docs 中找到了這個並進行了修改,只是一個簡單的TRITE :/
“一條線來統治他們”:)

public void downloadFile()
{
    GoogleCredential credential = GoogleCredential.FromFile( "your-json-file-from-gcp" );
    StorageClient storageClient = StorageClient.Create( credential );

    // eg: Images/MyImage.jpg
    string objectName = "what-file-you-want-to-download-from-what-folder";
    
    // eg: "c://CallItSomethingElseIfYouWant.jpg"
    string localPath = "where-you-want-to-store-it-AND-call-it";
    
    // eg: xxxxxxxx-xxxxx.appspot.com
    string bucketName = "xxxxxxxx-xxxxx.appspot.com";
    
    FileStream fileStream = File.OpenWrite( @localPath );

    // --- The Magic Line
    storageClient.DownloadObject( bucketName, objectName, fileStream );
    // --  

    fileStream.Flush();
    fileStream.Close();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM