当前位置: 首页>>代码示例>>C#>>正文


C# AmazonS3Client.GetObjectMetadata方法代码示例

本文整理汇总了C#中Amazon.S3.AmazonS3Client.GetObjectMetadata方法的典型用法代码示例。如果您正苦于以下问题:C# AmazonS3Client.GetObjectMetadata方法的具体用法?C# AmazonS3Client.GetObjectMetadata怎么用?C# AmazonS3Client.GetObjectMetadata使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Amazon.S3.AmazonS3Client的用法示例。


在下文中一共展示了AmazonS3Client.GetObjectMetadata方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: InstanceExists

 public bool InstanceExists(Guid instanceKey)
 {
     try
     {
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObjectMetadata(new GetObjectMetadataRequest()
             {
                 BucketName = Context.BucketName,
                 Key = string.Format("{0}/{1}/{2}", STR_INSTANCES_CONTAINER_PATH, instanceKey.ToString("N"), STR_INFO_FILE_NAME),
             })) { return true; }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return false;
         }
         else
         {
             throw new DeploymentException(string.Format("Failed getting instance with key \"{0}\"", instanceKey), awsEx);
         }
     }
 }
开发者ID:danielrbradley,项目名称:Plywood,代码行数:25,代码来源:Instances.cs

示例2: UploadToCdn

        private void UploadToCdn()
        {
            try
            {
                // one thread only
                if (Interlocked.CompareExchange(ref work, 1, 0) == 0)
                {
                    var @continue = false;
                    try
                    {
                        CdnItem item;
                        if (queue.TryDequeue(out item))
                        {
                            @continue = true;

                            var cdnpath = GetCdnPath(item.Bundle.Path);
                            var key = new Uri(cdnpath).PathAndQuery.TrimStart('/');
                            var etag = AmazonS3Util.GenerateChecksumForContent(item.Response.Content, false).ToLowerInvariant();

                            var config = new AmazonS3Config
                            {
                                ServiceURL = "s3.amazonaws.com",
                                CommunicationProtocol = Protocol.HTTP
                            };
                            using (var s3 = new AmazonS3Client(s3publickey, s3privatekey, config))
                            {
                                var upload = false;
                                try
                                {
                                    var request = new GetObjectMetadataRequest
                                    {
                                        BucketName = s3bucket,
                                        Key = key,
                                    };
                                    using (var response = s3.GetObjectMetadata(request))
                                    {
                                        upload = !string.Equals(etag, response.ETag.Trim('"'), StringComparison.InvariantCultureIgnoreCase);
                                    }
                                }
                                catch (AmazonS3Exception ex)
                                {
                                    if (ex.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        upload = true;
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }

                                if (upload)
                                {
                                    var request = new PutObjectRequest
                                    {
                                        BucketName = s3bucket,
                                        CannedACL = S3CannedACL.PublicRead,
                                        Key = key,
                                        ContentType = AmazonS3Util.MimeTypeFromExtension(Path.GetExtension(key).ToLowerInvariant()),
                                    };

                                    if (ClientSettings.GZipEnabled)
                                    {
                                        var compressed = new MemoryStream();
                                        using (var compression = new GZipStream(compressed, CompressionMode.Compress, true))
                                        {
                                            new MemoryStream(Encoding.UTF8.GetBytes(item.Response.Content)).CopyTo(compression);
                                        }
                                        request.InputStream = compressed;
                                        request.AddHeader("Content-Encoding", "gzip");
                                    }
                                    else
                                    {
                                        request.ContentBody = item.Response.Content;
                                    }

                                    var cache = TimeSpan.FromDays(365);
                                    request.AddHeader("Cache-Control", string.Format("public, maxage={0}", (int)cache.TotalSeconds));
                                    request.AddHeader("Expires", DateTime.UtcNow.Add(cache).ToString("R"));
                                    request.AddHeader("Etag", etag);
                                    request.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));

                                    using (s3.PutObject(request)) { }
                                }

                                item.Bundle.CdnPath = cdnpath;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        log.Error(err);
                    }
                    finally
                    {
                        work = 0;
                        if (@continue)
                        {
                            Action upload = () => UploadToCdn();
                            upload.BeginInvoke(null, null);
//.........这里部分代码省略.........
开发者ID:haoasqui,项目名称:ONLYOFFICE-Server,代码行数:101,代码来源:CdnTransform.cs

示例3: UpdateIndex

        public void UpdateIndex(string path, EntityIndex index)
        {
            var serialised = SerialiseIndex(index.Entries);
            var stream = new MemoryStream(serialised.Length);
            var writer = new StreamWriter(stream);
            writer.Write(serialised);
            writer.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            try
            {
                using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
                {
                    // Check that the index has not been updated before pushing the change - reduce the risks.
                    try
                    {
                        using (var objectMetaDataResponse = client.GetObjectMetadata(new GetObjectMetadataRequest()
                        {
                            BucketName = Context.BucketName,
                            Key = path,
                            ETagToMatch = index.ETag
                        }))
                        {

                        }
                    }
                    catch (AmazonS3Exception awsEx)
                    {
                        if (awsEx.StatusCode != System.Net.HttpStatusCode.NotFound)
                            throw;
                    }

                    using (var putResponse = client.PutObject(new PutObjectRequest()
                    {
                        BucketName = Context.BucketName,
                        Key = path,
                        GenerateMD5Digest = true,
                        InputStream = stream
                    })) { }
                }
            }
            catch (AmazonS3Exception awsEx)
            {
                throw new DeploymentException("Failed loading group index", awsEx);
            }
        }
开发者ID:danielrbradley,项目名称:Plywood,代码行数:45,代码来源:Indexes.cs

示例4: DeployPush

        public void DeployPush(string appName, string s3Location, string sourcePath)
        {
            var s3 = new S3LocationParser(s3Location);

            using (var s3Client = new Amazon.S3.AmazonS3Client(Credentials, Amazon.RegionEndpoint.USEast1))
            {
                var getRequest = new Amazon.S3.Model.GetObjectMetadataRequest
                {
                    BucketName = s3.BucketName,
                    Key = s3.Key
                };

                try
                {
                    var getResponse = s3Client.GetObjectMetadata(getRequest);

                    // If we got this far, the file already exists in the S3 bucket, so get out!
                    throw new S3KeyAlreadyExistsException(s3);
                }
                catch (AmazonS3Exception ex)
                {
                    // If we got this far, then it's because the S3 file doesn't exist.
                    // Therefore, it's OK to upload with this key.
                    var zipFileName = s3.FileName;
                    var g = Guid.NewGuid().ToString();
                    var outputFile = Path.Combine(Path.GetTempPath(), g + ".tmp");
                    ZipFile.CreateFromDirectory(sourcePath, outputFile);
                    var zipFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), zipFileName);

                    if (File.Exists(zipFile))
                        File.Delete(zipFile);

                    File.Move(outputFile, zipFile);

                    var putRequest = new Amazon.S3.Model.PutObjectRequest
                    {
                        BucketName = s3.BucketName,
                        FilePath = zipFile,
                        Key = s3.Key
                    };

                    var putResponse = s3Client.PutObject(putRequest);

                    using (var cdClient = new Amazon.CodeDeploy.AmazonCodeDeployClient(Credentials, Amazon.RegionEndpoint.USEast1))
                    {
                        var revLocation = new Amazon.CodeDeploy.Model.RevisionLocation
                        {
                            RevisionType = Amazon.CodeDeploy.RevisionLocationType.S3,
                            S3Location = new Amazon.CodeDeploy.Model.S3Location
                                            {
                                                Bucket = s3.BucketName,
                                                BundleType = Amazon.CodeDeploy.BundleType.Zip,
                                                Key = s3.Key
                                            }
                        };

                        var regRequest = new Amazon.CodeDeploy.Model.RegisterApplicationRevisionRequest
                        {
                            ApplicationName = appName,
                            Revision = revLocation
                        };

                        var regResponse = cdClient.RegisterApplicationRevision(regRequest);

                        var x = 0;
                    }
                }
            }
        }
开发者ID:pgjasinski,项目名称:AwsCodeDeployUtility,代码行数:69,代码来源:AmazonEngine.cs

示例5: putObject

        public static String putObject(HttpPostedFileBase file, String name)
        {
            //Create a unique file name with help of the user name that is unique too
            String filename = name + file.FileName;
            String url = server + bucket + "/" + filename;

            using (IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.EUCentral1))
            {

                //Check if file exists
                var s3FileInfo = new Amazon.S3.IO.S3FileInfo(client, bucket, filename);
                if (s3FileInfo.Exists)
                {
                    GetObjectMetadataRequest request = new GetObjectMetadataRequest();
                    request.BucketName = bucket;
                    request.Key = filename;

                    GetObjectMetadataResponse response = client.GetObjectMetadata(request);
                    //Get tag from Amazon file
                    String S3Tag = response.ETag.Replace("/", "").Replace("\"", "");

                    using (var md5 = MD5.Create())
                    {
                        using (var stream = file.InputStream)
                        {
                            //Get tag from local file
                            stream.Position = 0;
                            String fileTag = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
                            //Compare both tags, if they match there´s no need to upload the image
                            if (fileTag == S3Tag) return url;
                            return null;
                        }
                    }

                }
                else
                {
                    int size = file.ContentLength;

                    //Upload image to amazon s3
                    PutObjectRequest request = new PutObjectRequest();
                    request.CannedACL = S3CannedACL.PublicRead;
                    request.BucketName = bucket;
                    request.ContentType = file.ContentType;
                    request.Key = filename;
                    request.InputStream = file.InputStream;
                    client.PutObject(request);

                    //Update traffic after upload
                    PictogramsDb.UpdateTraffic(name, size);

                }
            }

            return url;
        }
开发者ID:GSLourenco,项目名称:MyLastVersion,代码行数:56,代码来源:PictoUploader.cs

示例6: ObjectSamples

        public void ObjectSamples()
        {
            {
                #region ListObjects Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // List all objects
                ListObjectsRequest listRequest = new ListObjectsRequest
                {
                    BucketName = "SampleBucket",
                };

                ListObjectsResponse listResponse;
                do
                {
                    // Get a list of objects
                    listResponse = client.ListObjects(listRequest);
                    foreach (S3Object obj in listResponse.S3Objects)
                    {
                        Console.WriteLine("Object - " + obj.Key);
                        Console.WriteLine(" Size - " + obj.Size);
                        Console.WriteLine(" LastModified - " + obj.LastModified);
                        Console.WriteLine(" Storage class - " + obj.StorageClass);
                    }

                    // Set the marker property
                    listRequest.Marker = listResponse.NextMarker;
                } while (listResponse.IsTruncated);

                #endregion
            }

            {
                #region GetObject Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a GetObject request
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1"
                };

                // Issue request and remember to dispose of the response
                using (GetObjectResponse response = client.GetObject(request))
                {
                    using (StreamReader reader = new StreamReader(response.ResponseStream))
                    {
                        string contents = reader.ReadToEnd();
                        Console.WriteLine("Object - " + response.Key);
                        Console.WriteLine(" Version Id - " + response.VersionId);
                        Console.WriteLine(" Contents - " + contents);
                    }
                }

                #endregion
            }

            {
                #region GetObjectMetadata Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();


                // Create a GetObjectMetadata request
                GetObjectMetadataRequest request = new GetObjectMetadataRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1"
                };

                // Issue request and view the response
                GetObjectMetadataResponse response = client.GetObjectMetadata(request);
                Console.WriteLine("Content Length - " + response.ContentLength);
                Console.WriteLine("Content Type - " + response.Headers.ContentType);
                if (response.Expiration != null)
                {
                    Console.WriteLine("Expiration Date - " + response.Expiration.ExpiryDate);
                    Console.WriteLine("Expiration Rule Id - " + response.Expiration.RuleId);
                }

                #endregion
            }

            {
                #region PutObject Sample 1

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a PutObject request
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
//.........这里部分代码省略.........
开发者ID:rajdotnet,项目名称:aws-sdk-net,代码行数:101,代码来源:BaseS3Samples.cs

示例7: TargetAppVersionChanged

 public VersionCheckResult TargetAppVersionChanged(Guid targetKey, Guid appKey, Guid localVersionKey)
 {
     try
     {
         string localETag;
         using (var localKeyStream = Utils.Serialisation.Serialise(localVersionKey))
         {
             localETag = Utils.Validation.GenerateETag(localKeyStream);
         }
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObjectMetadata(new GetObjectMetadataRequest()
             {
                 BucketName = Context.BucketName,
                 Key = GetTargetAppVersionInfoPath(targetKey, appKey),
             }))
             {
                 if (res.ETag == localETag)
                     return VersionCheckResult.NotChanged;
                 else
                     return VersionCheckResult.Changed;
             }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return VersionCheckResult.NotSet;
         }
         else
         {
             throw new DeploymentException(string.Format("Failed checking for version updates for app with key \"{0}\" and target with the key \"{1}\".", appKey, targetKey), awsEx);
         }
     }
 }
开发者ID:danielrbradley,项目名称:Plywood,代码行数:36,代码来源:TargetAppVersions.cs

示例8: UploadToCdn

        private void UploadToCdn()
        {
            try
            {
                // one thread only
                if (Interlocked.CompareExchange(ref work, 1, 0) == 0)
                {
                    var @continue = false;
                    try
                    {
                        CdnItem item;
                        if (queue.TryDequeue(out item))
                        {
                            @continue = true;

                            var cdnpath = GetCdnPath(item.Bundle.Path);
                            var key = new Uri(cdnpath).PathAndQuery.TrimStart('/');
                            var contentMD5 = Hasher.Base64Hash(item.Response.Content, HashAlg.MD5);
                            var compressed = new MemoryStream();

                            if (ClientSettings.GZipEnabled)
                            {
                                using (var compression = new GZipStream(compressed, CompressionMode.Compress, true))
                                {
                                    new MemoryStream(Encoding.UTF8.GetBytes(item.Response.Content)).CopyTo(compression);
                                }
                                contentMD5 = Hasher.Base64Hash(compressed.GetCorrectBuffer(), HashAlg.MD5);
                            }

                            var config = new AmazonS3Config
                            {
                                RegionEndpoint = RegionEndpoint.GetBySystemName(s3region),
                                UseHttp = true
                            };
                            using (var s3 = new AmazonS3Client(s3publickey, s3privatekey, config))
                            {
                                var upload = false;
                                try
                                {
                                    var request = new GetObjectMetadataRequest
                                        {
                                        BucketName = s3bucket,
                                        Key = key
                                    };
                                    var response = s3.GetObjectMetadata(request);
                                    upload = !string.Equals(contentMD5, response.Metadata["x-amz-meta-etag"], StringComparison.InvariantCultureIgnoreCase);
                                }
                                catch (AmazonS3Exception ex)
                                {
                                    if (ex.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        upload = true;
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }

                                if (upload)
                                {
                                    var request = new PutObjectRequest
                                    {
                                        BucketName = s3bucket,
                                        CannedACL = S3CannedACL.PublicRead,
                                        Key = key,
                                        ContentType = AmazonS3Util.MimeTypeFromExtension(Path.GetExtension(key).ToLowerInvariant())
                                    };

                                    if (ClientSettings.GZipEnabled)
                                    {
                                        request.InputStream = compressed;
                                        request.Headers.ContentEncoding = "gzip";
                                    }
                                    else
                                    {
                                        request.ContentBody = item.Response.Content;
                                    }

                                    var cache = TimeSpan.FromDays(365);
                                    request.Headers.CacheControl = string.Format("public, maxage={0}", (int) cache.TotalSeconds);
                                    request.Headers.Expires = DateTime.UtcNow.Add(cache);
                                    request.Headers.ContentMD5 = contentMD5;
                                    request.Headers["x-amz-meta-etag"] = contentMD5;
                                    //request.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));

                                    s3.PutObject(request);
                                }

                                item.Bundle.CdnPath = cdnpath;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        log.Error(err);
                    }
                    finally
                    {
                        work = 0;
//.........这里部分代码省略.........
开发者ID:vipwan,项目名称:CommunityServer,代码行数:101,代码来源:CdnTransform.cs

示例9: ScanProfile


//.........这里部分代码省略.........
                    AmazonS3Client BS3Client = new AmazonS3Client(credential, S3C);

                    var createddate = abucket.CreationDate;
                    string owner = "";
                    string grants = "";
                    string tags = "";
                    string lastaccess = "";
                    string defaultpage = "";
                    string website = "";
                    //Now start pulling der einen data.

                    GetACLRequest GACR = new GetACLRequest();
                    GACR.BucketName = name;
                    var ACL = BS3Client.GetACL(GACR);
                    var grantlist = ACL.AccessControlList;
                    owner = grantlist.Owner.DisplayName;
                    foreach (var agrant in grantlist.Grants)
                    {
                        if (grants.Length > 1) grants += "\n";
                        var gName = agrant.Grantee.DisplayName;
                        var gType = agrant.Grantee.Type.Value;
                        var aMail = agrant.Grantee.EmailAddress;

                        if (gType.Equals("Group"))
                        {
                            grants +=  gType + " - " + agrant.Grantee.URI + " - " + agrant.Permission + " - " + aMail  ;
                        }
                        else
                        {
                            grants += gName + " - "+ agrant.Permission + " - " + aMail;
                        }
                    }

                    GetObjectMetadataRequest request = new GetObjectMetadataRequest();
                    request.BucketName = name;
                    GetObjectMetadataResponse MDresponse = BS3Client.GetObjectMetadata(request);
                    lastaccess = MDresponse.LastModified.ToString();
                    //defaultpage = MDresponse.WebsiteRedirectLocation;

                    GetBucketWebsiteRequest GBWReq = new GetBucketWebsiteRequest();
                    GBWReq.BucketName = name;
                    GetBucketWebsiteResponse GBWRes = BS3Client.GetBucketWebsite(GBWReq);

                    defaultpage = GBWRes.WebsiteConfiguration.IndexDocumentSuffix;

                    if (defaultpage != null)
                    {
                        website = @"http://" + name + @".s3-website-" + region + @".amazonaws.com/" + defaultpage;
                    }

                    //Amazon.S3.Model.req

                    abucketrow["AccountID"] = accountid;
                    abucketrow["Profile"] = aprofile;
                    abucketrow["Bucket"] = name;
                    abucketrow["Region"] = region;
                    abucketrow["CreationDate"] = createddate.ToString();
                    abucketrow["LastAccess"] = lastaccess;
                    abucketrow["Owner"] = owner;
                    abucketrow["Grants"] = grants;

                    abucketrow["WebsiteHosting"] = website;
                    abucketrow["Logging"] = "X";
                    abucketrow["Events"] = "X";
                    abucketrow["Versioning"] = "X";
                    abucketrow["LifeCycle"] = "X";
开发者ID:ptierno,项目名称:AWSTrycorder,代码行数:67,代码来源:MainWindow.xaml.cs

示例10: VersionExists

 internal bool VersionExists(Guid key)
 {
     try
     {
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObjectMetadata(new GetObjectMetadataRequest()
             {
                 BucketName = Context.BucketName,
                 Key = string.Format("{0}/{1}/{2}", STR_VERSIONS_CONTAINER_PATH, key.ToString("N"), STR_INFO_FILE_NAME),
             })) { return true; }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return false;
         }
         else
         {
             throw new DeploymentException(string.Format("Failed checking if version with key \"{0}\" exists.", key), awsEx);
         }
     }
     catch (Exception ex)
     {
         throw new DeploymentException(string.Format("Failed checking if version with key \"{0}\" exists.", key), ex);
     }
 }
开发者ID:danielrbradley,项目名称:Plywood,代码行数:29,代码来源:Versions.cs


注:本文中的Amazon.S3.AmazonS3Client.GetObjectMetadata方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。