简体   繁体   中英

Upload files to Google cloud storage using c#

I am using the below sample code to upload the file into the Google cloud storage (Bucket). it is working properly when executed from my local machine. But is giving me the following exception when executed in the production environment. Program code.

public class Program
{
    static void Main(string[] args)
    {
        try
        {
            string bucketName = "bucketName";
            string sharedkeyFilePath = GetFilePath("privateKey.json");
            GoogleCredential credential = null;
            using (var jsonStream = new FileStream(sharedkeyFilePath, FileMode.Open,
                FileAccess.Read, FileShare.Read))
            {
                credential = GoogleCredential.FromStream(jsonStream);
            }
            var storageClient = StorageClient.Create(credential);
            string filetoUpload = GetFilePath("demo.txt");
            using (var fileStream = new FileStream(filetoUpload, FileMode.Open,
                FileAccess.Read, FileShare.Read))
            {
                storageClient.UploadObject(bucketName, "demo.txt", "text/plain", fileStream);
            }
            Console.WriteLine("uploaded the file successfully");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public static string GetFilePath(string filename)
    {
        return GetFilePath(Assembly.GetCallingAssembly().Location, filename);
    }
    public static string GetFilePath(string path, string filename)
    {
        return path.Substring(0, path.LastIndexOf("\\")) + @"\" + filename;
    }
}

Exception Details:

`A task was canceled.
  at Google.Cloud.Storage.V1.StorageClientImpl.UploadHelper.CheckFinalProgress()
   at Google.Cloud.Storage.V1.StorageClientImpl.UploadHelper.Execute()
   at Google.Cloud.Storage.V1.StorageClientImpl.UploadObject(Object destination, Stream source, UploadObjectOptions options, IProgress`1 progress)
   at Google.Cloud.Storage.V1.StorageClientImpl.UploadObject(String bucket, String objectName, String contentType, Stream source, UploadObjectOptions options, IProgress`1 progress)
   at gcsUpload.Program.Main(String[] args) in d:\Ganesh Deshmukh\Projects\GCS\gcsUpload\gcsUpload\Program.cs:line 49
Google.Cloud.Storage.V1`

There was an issue with firewall settings. Above code work properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM