使用C#将文件上传到Google云存储

时间:2019-05-03 10:17:50

标签: c# google-cloud-platform google-cloud-storage

我正在使用以下示例代码将文件上传到Google云存储(存储桶)中。从我的本地计算机执行时,它工作正常。但是在生产环境中执行时给我以下异常。 程序代码。

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;
    }
}

异常详细信息:

`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`

1 个答案:

答案 0 :(得分:0)

防火墙设置存在问题。上面的代码正常工作。