public DeleteObject ( |
||
request | Container for the necessary parameters to execute the DeleteObject service method. | |
Результат |
public void DeleteFile(String filename) { String key = filename; var amazonClient = new AmazonS3Client(_keyPublic, _keySecret); var deleteObjectRequest = new DeleteObjectRequest { BucketName = _bucket, Key = key }; var response = amazonClient.DeleteObject(deleteObjectRequest); }
public static void DeletingAnObject(AmazonS3Client client, string bucketName, string keyName) { DeleteObjectRequest request = new DeleteObjectRequest(); request.WithBucketName(bucketName) .WithKey(keyName); S3Response response = client.DeleteObject(request); response.Dispose(); }
public static void DeleteFromBucket(string bucketName, string key) { using (var client = new AmazonS3Client(Settings.AccessKey, Settings.Secret)) { var request = new DeleteObjectRequest() { BucketName = bucketName, Key = key }; client.DeleteObject(request); } }
private void EditFile(HttpChallenge httpChallenge, bool delete, TextWriter msg) { var filePath = httpChallenge.FilePath; // We need to strip off any leading '/' in the path or // else it creates a path with an empty leading segment if (filePath.StartsWith("/")) { filePath = filePath.Substring(1); } using (var s3 = new Amazon.S3.AmazonS3Client( CommonParams.ResolveCredentials(), CommonParams.RegionEndpoint)) { if (delete) { LOG.Debug("Deleting S3 object at Bucket [{0}] and Key [{1}]", BucketName, filePath); var s3Requ = new Amazon.S3.Model.DeleteObjectRequest { BucketName = BucketName, Key = filePath, }; var s3Resp = s3.DeleteObject(s3Requ); if (LOG.IsDebugEnabled) { LOG.Debug("Delete response: [{0}]", NLog.Targets.DefaultJsonSerializer.Instance.SerializeObject(s3Resp)); } msg.WriteLine("* Challenge Response has been deleted from S3"); msg.WriteLine(" at Bucket/Key: [{0}/{1}]", BucketName, filePath); } else { var s3Requ = new Amazon.S3.Model.PutObjectRequest { BucketName = BucketName, Key = filePath, ContentBody = httpChallenge.FileContent, ContentType = ContentType, CannedACL = S3CannedAcl, }; var s3Resp = s3.PutObject(s3Requ); msg.WriteLine("* Challenge Response has been written to S3"); msg.WriteLine(" at Bucket/Key: [{0}/{1}]", BucketName, filePath); msg.WriteLine("* Challenge Response should be accessible with a MIME type of [text/json]"); msg.WriteLine(" at: [{0}]", httpChallenge.FileUrl); } } }
public void S3DeleteItem(string bucketName, string keyName) { //ref: http://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html using (var client = new AmazonS3Client(this.AcesssKey, this.SecretKey, this.Region)) { DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest { BucketName = bucketName, Key = keyName }; client.DeleteObject(deleteObjectRequest); System.Diagnostics.Debug.WriteLine(string.Format("AwsS3 -- Deleted {0}", keyName)); } }
public static void SoftDeleteFolders(ControllerConfiguration context, IEnumerable<string> folders) { if (context == null) throw new ArgumentNullException("context", "Context cannot be null."); if (folders == null) throw new ArgumentNullException("folders", "Folders cannot be null."); using (var client = new AmazonS3Client(context.AwsAccessKeyId, context.AwsSecretAccessKey)) { foreach (var folder in folders) { int maxResults = 100; int lastCount = maxResults; while (maxResults == lastCount) { using (var listResponse = client.ListObjects(new ListObjectsRequest() { BucketName = context.BucketName, Prefix = folder, })) { lastCount = listResponse.S3Objects.Count; Parallel.ForEach(listResponse.S3Objects, folderObject => { using (var copyResponse = client.CopyObject(new CopyObjectRequest() { SourceBucket = context.BucketName, DestinationBucket = context.BucketName, SourceKey = folderObject.Key, DestinationKey = ".recycled/" + folderObject.Key, })) { } }); Parallel.ForEach(listResponse.S3Objects, folderObject => { using (var deleteReponse = client.DeleteObject(new DeleteObjectRequest() { BucketName = context.BucketName, Key = folderObject.Key, })) { } }); } } } } }
public static void DeleteAllBucketItems(string bucketName) { using (var client = new AmazonS3Client(Settings.AccessKey, Settings.Secret)) { var request = new ListObjectsRequest { BucketName = bucketName }; var response = client.ListObjects(request); foreach (var entry in response.S3Objects) { client.DeleteObject(bucketName, entry.Key); } } }
public static void DeleteFile(string key) { var s3Config = new AmazonS3Config() { ServiceURL = "http://" + _s3_bucket_region }; using (var cli = new AmazonS3Client( _s3_access_key, _s3_secret_access_key, s3Config)) { DeleteObjectRequest req = new DeleteObjectRequest() { BucketName = _s3_bucket_name, Key = key }; var response = cli.DeleteObject(req); if(response.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { throw new Exception("s3: delete file failed."); } } }
/// <summary>AWS S3 단일 객체 삭제</summary> public bool DeleteObject(string pKey) { try { using (AmazonS3Client client = new AmazonS3Client()) { DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest { BucketName = strAwsBucketName, Key = pKey }; DeleteObjectResponse response = client.DeleteObject(deleteObjectRequest); return true; } } catch (AmazonS3Exception amazonS3Exception) { throw amazonS3Exception; } }
private void EditFile(HttpChallenge httpChallenge, bool delete) { var filePath = httpChallenge.FilePath; // We need to strip off any leading '/' in the path or // else it creates a path with an empty leading segment if (filePath.StartsWith("/")) { filePath = filePath.Substring(1); } using (var s3 = new Amazon.S3.AmazonS3Client( CommonParams.ResolveCredentials(), CommonParams.RegionEndpoint)) { if (delete) { var s3Requ = new Amazon.S3.Model.DeleteObjectRequest { BucketName = BucketName, Key = filePath, }; var s3Resp = s3.DeleteObject(s3Requ); } else { var s3Requ = new Amazon.S3.Model.PutObjectRequest { BucketName = BucketName, Key = filePath, ContentBody = httpChallenge.FileContent, ContentType = ContentType, CannedACL = S3CannedAcl, }; var s3Resp = s3.PutObject(s3Requ); } } }
private void EditFile(HttpChallenge httpChallenge, bool delete) { var filePath = httpChallenge.FilePath; // We need to strip off any leading '/' in the path or // else it creates a path with an empty leading segment if (filePath.StartsWith("/")) filePath = filePath.Substring(1); using (var s3 = new Amazon.S3.AmazonS3Client( CommonParams.ResolveCredentials(), CommonParams.RegionEndpoint)) { if (delete) { var s3Requ = new Amazon.S3.Model.DeleteObjectRequest { BucketName = BucketName, Key = filePath, }; var s3Resp = s3.DeleteObject(s3Requ); } else { var s3Requ = new Amazon.S3.Model.PutObjectRequest { BucketName = BucketName, Key = filePath, ContentBody = httpChallenge.FileContent, ContentType = ContentType, CannedACL = S3CannedAcl, }; var s3Resp = s3.PutObject(s3Requ); } } }
public void ReplaceAdImages(ref Ad ad, FileName[] filenames) { string newFileName = ""; int count = 1; var id = ad.Id; var imaa = db.AdImages.Where(x => x.adId.Equals(id)).Count(); count = imaa + 1; for (int i = 1; i < filenames.Length; i++) { IAmazonS3 client; try { using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1)) { GetObjectRequest request = new GetObjectRequest { BucketName = _bucketName, Key = _folderName + filenames[i].fileName }; using (GetObjectResponse response = client.GetObject(request)) { string filename = filenames[i].fileName; if (!System.IO.File.Exists(filename)) { string extension = System.IO.Path.GetExtension(filenames[i].fileName); newFileName = ad.Id.ToString() + "_" + count + extension; client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1); CopyObjectRequest request1 = new CopyObjectRequest() { SourceBucket = _bucketName, SourceKey = _folderName + filename, DestinationBucket = _bucketName, CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE DestinationKey = _folderName + newFileName }; CopyObjectResponse response1 = client.CopyObject(request1); AdImage image = new AdImage(); image.imageExtension = extension; image.adId = ad.Id; db.AdImages.Add(image); db.SaveChanges(); count++; DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest { BucketName = _bucketName, Key = _folderName + filenames[i].fileName }; AmazonS3Config config = new AmazonS3Config(); config.ServiceURL = "https://s3.amazonaws.com/"; using (client = Amazon.AWSClientFactory.CreateAmazonS3Client( _awsAccessKey, _awsSecretKey, config)) { client.DeleteObject(deleteObjectRequest); } } } } } catch (Exception e) { } } }
public bool MoveFile(string sourcePath, string sourceBucket, string destinationPath, string destinationBucket) { try { var request = new CopyObjectRequest { DestinationBucket = destinationBucket, DestinationKey = destinationPath, SourceKey = sourcePath, SourceBucket = sourceBucket }; using (var s3 = new AmazonS3Client(_connectionInfo.AccessKey, _connectionInfo.SecretKey, new AmazonS3Config {ServiceURL = "http://s3.amazonaws.com"})) { var response = s3.CopyObject(request); if (response.HttpStatusCode == HttpStatusCode.OK) { s3.DeleteObject(new DeleteObjectRequest() {BucketName = sourceBucket, Key = sourcePath}); } } return true; } catch (Exception ex) { Log.Error("Error Moving file", ex); return false; } }
public bool deleteFile(string keyName, string bucketName) { try { IAmazonS3 client; client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2); DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest { BucketName = bucketName, Key = keyName }; using (client = Amazon.AWSClientFactory.CreateAmazonS3Client( "AKIAIM2K2FSR2DC6KMSA", "yZ2+Mzs8w1iYGPplXNkLfWtOqif9Rad5wjGu3/zn", Amazon.RegionEndpoint.USWest2)) { var response = client.DeleteObject(deleteObjectRequest); } } catch (Exception) { return false; } return true; }
public static void DownloadFiles(string accessKey, string secretKey, string bucketName, string s3FolderName, string saveFolder, bool removeFromS3AfterDownload, Action<GetObjectResponse> onFileDownload = null, Action<DeleteObjectResponse> onFileDelete = null) { Log.DebugFormat("Starting download of files like '{0}' to '{1}'", bucketName + "/" + s3FolderName, saveFolder); if (!Directory.Exists(saveFolder)) { Log.ErrorFormat("Couldn't find folder {0}", saveFolder); throw new ArgumentException(string.Format("Could not find folder {0}", saveFolder)); } using (var client = new AmazonS3Client(accessKey, secretKey, new AmazonS3Config { ServiceURL = "http://s3.amazonaws.com" })) { var marker = default(string); do { var listResponse = ListFiles(accessKey, secretKey, bucketName, s3FolderName, marker); foreach (var f in listResponse.S3Objects.Select(x => x.Key)) { var req = new GetObjectRequest { BucketName = bucketName, Key = f }; var match = Regex.Match(f, FilepathPattern); var filename = match.Groups["filename_without_extension"].Value; var extension = match.Groups["extension"].Value; var savePath = Path.Combine(saveFolder, filename + "." + extension); var transferPath = savePath + ".tran"; Log.DebugFormat("Downloading '{0}' to '{1}'", bucketName + "/" + f, transferPath); var res = client.GetObject(req); if (onFileDownload != null) { Log.Debug("Running onFileDownload filter"); onFileDownload(res); } res.WriteResponseStreamToFile(transferPath, false); if (removeFromS3AfterDownload) { var deleteRequest = new DeleteObjectRequest { BucketName = bucketName, Key = f }; Log.DebugFormat("Deleting '{0}' from S3", bucketName + "/" + f); var deleteResponse = client.DeleteObject(deleteRequest); if (onFileDelete != null) { Log.Debug("Running onFileDelete filter"); onFileDelete(deleteResponse); } } //try to move the file to it's original save spot Log.DebugFormat("Moving file '{0}' to '{1}'", transferPath, savePath); for (var retryCount = 0; retryCount < 3; retryCount++) { try { File.Move(transferPath, savePath); break; } catch (Exception ex) { if (retryCount == 2) { Log.Error("Failed to move file. Exceeded retry count", ex); throw; } Log.ErrorFormat("Failed to move file from '{0}', to '{1}'. Retry: {2}", transferPath, savePath, retryCount); Thread.Sleep(1000); } } } marker = listResponse.IsTruncated ? listResponse.NextMarker : default(string); } while (marker != default(string)); } Log.Debug("Finished downloading files from s3"); }
public static String ReplaceObject(HttpPostedFileBase file, String name) { String filename = name + file.FileName; String url = server + bucket + "/" + filename; ; using (IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.EUCentral1)) { //check if file exists and if so deletes it var s3FileInfo = new Amazon.S3.IO.S3FileInfo(client, bucket, filename); if (s3FileInfo.Exists) { DeleteObjectRequest drequest = new DeleteObjectRequest(); drequest.BucketName = bucket; drequest.Key = filename; client.DeleteObject(drequest); } //update the new file int size = file.ContentLength; 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 PictogramsDb.UpdateTraffic(name, size); } return url; }
public void BucketSamples() { { #region ListBuckets Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Issue call ListBucketsResponse response = client.ListBuckets(); // View response data Console.WriteLine("Buckets owner - {0}", response.Owner.DisplayName); foreach (S3Bucket bucket in response.Buckets) { Console.WriteLine("Bucket {0}, Created on {1}", bucket.BucketName, bucket.CreationDate); } #endregion } { #region BucketPolicy Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Put sample bucket policy (overwrite an existing policy) string newPolicy = @"{ ""Statement"":[{ ""Sid"":""BasicPerms"", ""Effect"":""Allow"", ""Principal"": ""*"", ""Action"":[""s3:PutObject"",""s3:GetObject""], ""Resource"":[""arn:aws:s3:::samplebucketname/*""] }]}"; PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest { BucketName = "SampleBucket", Policy = newPolicy }; client.PutBucketPolicy(putRequest); // Retrieve current policy GetBucketPolicyRequest getRequest = new GetBucketPolicyRequest { BucketName = "SampleBucket" }; string policy = client.GetBucketPolicy(getRequest).Policy; Console.WriteLine(policy); Debug.Assert(policy.Contains("BasicPerms")); // Delete current policy DeleteBucketPolicyRequest deleteRequest = new DeleteBucketPolicyRequest { BucketName = "SampleBucket" }; client.DeleteBucketPolicy(deleteRequest); // Retrieve current policy and verify that it is null policy = client.GetBucketPolicy(getRequest).Policy; Debug.Assert(policy == null); #endregion } { #region GetBucketLocation Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request GetBucketLocationRequest request = new GetBucketLocationRequest { BucketName = "SampleBucket" }; // Issue call GetBucketLocationResponse response = client.GetBucketLocation(request); // View response data Console.WriteLine("Bucket location - {0}", response.Location); #endregion } { #region PutBucket Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request PutBucketRequest request = new PutBucketRequest { BucketName = "SampleBucket", BucketRegion = S3Region.EU, // set region to EU CannedACL = S3CannedACL.PublicRead // make bucket publicly readable }; // Issue call PutBucketResponse response = client.PutBucket(request); #endregion } { #region DeleteBucket Sample 1 // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request DeleteBucketRequest request = new DeleteBucketRequest { BucketName = "SampleBucket" }; // Issue call DeleteBucketResponse response = client.DeleteBucket(request); #endregion } { #region DeleteBucket Sample 2 // Create a client AmazonS3Client client = new AmazonS3Client(); // List and delete 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) { // Delete each object client.DeleteObject(new DeleteObjectRequest { BucketName = "SampleBucket", Key = obj.Key }); } // Set the marker property listRequest.Marker = listResponse.NextMarker; } while (listResponse.IsTruncated); // Construct DeleteBucket request DeleteBucketRequest request = new DeleteBucketRequest { BucketName = "SampleBucket" }; // Issue call DeleteBucketResponse response = client.DeleteBucket(request); #endregion } { #region LifecycleConfiguration Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Put sample lifecycle configuration (overwrite an existing configuration) LifecycleConfiguration newConfiguration = new LifecycleConfiguration { Rules = new List<LifecycleRule> { // Rule to delete keys with prefix "Test-" after 5 days new LifecycleRule { Prefix = "Test-", Expiration = new LifecycleRuleExpiration { Days = 5 } }, // Rule to delete keys in subdirectory "Logs" after 2 days new LifecycleRule { Prefix = "Logs/", Expiration = new LifecycleRuleExpiration { Days = 2 }, Id = "log-file-removal" } } }; PutLifecycleConfigurationRequest putRequest = new PutLifecycleConfigurationRequest { BucketName = "SampleBucket", Configuration = newConfiguration }; client.PutLifecycleConfiguration(putRequest); // Retrieve current configuration GetLifecycleConfigurationRequest getRequest = new GetLifecycleConfigurationRequest { BucketName = "SampleBucket" }; LifecycleConfiguration configuration = client.GetLifecycleConfiguration(getRequest).Configuration; Console.WriteLine("Configuration contains {0} rules", configuration.Rules.Count); foreach (LifecycleRule rule in configuration.Rules) { Console.WriteLine("Rule"); Console.WriteLine(" Prefix = " + rule.Prefix); Console.WriteLine(" Expiration (days) = " + rule.Expiration.Days); Console.WriteLine(" Id = " + rule.Id); Console.WriteLine(" Status = " + rule.Status); } // Put a new configuration and overwrite the existing configuration configuration.Rules.RemoveAt(0); // remove first rule client.PutLifecycleConfiguration(putRequest); // Delete current configuration DeleteLifecycleConfigurationRequest deleteRequest = new DeleteLifecycleConfigurationRequest { BucketName = "SampleBucket" }; client.DeleteLifecycleConfiguration(deleteRequest); // Retrieve current configuration and verify that it is null configuration = client.GetLifecycleConfiguration(getRequest).Configuration; Debug.Assert(configuration == null); #endregion } }
public virtual void RemoveLabBuckets(AmazonS3Client s3Client, List<string> bucketNames) { foreach (var bucketName in bucketNames) { try { ListObjectsResponse listObjectsResponse = s3Client.ListObjects(new ListObjectsRequest {BucketName = bucketName}); foreach (var s3Object in listObjectsResponse.S3Objects) { var deleteObjectRequest = new DeleteObjectRequest { BucketName = bucketName, Key = s3Object.Key }; s3Client.DeleteObject(deleteObjectRequest); } s3Client.DeleteBucket(new DeleteBucketRequest {BucketName = bucketName}); } catch (AmazonS3Exception s3E) { if (!s3E.ErrorCode.Equals("NoSuchBucket")) { // This error wasn't expected, so rethrow. throw; } } } }
public void SetTargetAppVersion(Guid targetKey, Guid appKey, Guid? versionKey) { try { using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey)) { string targetAppVersionInfoPath = GetTargetAppVersionInfoPath(targetKey, appKey); if (versionKey.HasValue) { using (var keyStream = Utils.Serialisation.Serialise(versionKey.Value)) { // Put using (var res = client.PutObject(new PutObjectRequest() { BucketName = Context.BucketName, Key = targetAppVersionInfoPath, InputStream = keyStream, GenerateMD5Digest = true, })) { } } } else { // Delete using (var res = client.DeleteObject(new DeleteObjectRequest() { BucketName = Context.BucketName, Key = targetAppVersionInfoPath, })) { } } } } catch (AmazonS3Exception awsEx) { throw new DeploymentException(string.Format("Failed setting version for app with key \"{0}\" and target with the key \"{1}\".", appKey, targetKey), awsEx); } }
/// <summary> /// delete the filr from s3 /// </summary> /// <param name="PathName"></param> /// <param name="FileName"></param> /// <returns></returns> public bool DeleteFile(string PathName, string FileName) { try { //amazon client using (var client = new AmazonS3Client()) { //delete request using (var response = client.DeleteObject(new DeleteObjectRequest() .WithBucketName(PathName) .WithKey(FileName))) { return true; } } } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } return false; }
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", ContentBody = "This is sample content..." }; // Put object PutObjectResponse response = client.PutObject(request); #endregion } { #region PutObject Sample 2 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a PutObject request PutObjectRequest request = new PutObjectRequest { BucketName = "SampleBucket", Key = "Item1", FilePath = "contents.txt" }; // Put object PutObjectResponse response = client.PutObject(request); #endregion } { #region PutObject Sample 3 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a PutObject request PutObjectRequest request = new PutObjectRequest { BucketName = "SampleBucket", Key = "Item1", }; using (FileStream stream = new FileStream("contents.txt", FileMode.Open)) { request.InputStream = stream; // Put object PutObjectResponse response = client.PutObject(request); } #endregion } { #region DeleteObject Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a DeleteObject request DeleteObjectRequest request = new DeleteObjectRequest { BucketName = "SampleBucket", Key = "Item1" }; // Issue request client.DeleteObject(request); #endregion } { #region DeleteObjects Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a DeleteObject request DeleteObjectsRequest request = new DeleteObjectsRequest { BucketName = "SampleBucket", Objects = new List<KeyVersion> { new KeyVersion() {Key = "Item1"}, // Versioned item new KeyVersion() { Key = "Item2", VersionId = "Rej8CiBxcZKVK81cLr39j27Y5FVXghDK", }, // Item in subdirectory new KeyVersion() { Key = "Logs/error.txt"} } }; try { // Issue request DeleteObjectsResponse response = client.DeleteObjects(request); } catch (DeleteObjectsException doe) { // Catch error and list error details DeleteObjectsResponse errorResponse = doe.Response; foreach (DeletedObject deletedObject in errorResponse.DeletedObjects) { Console.WriteLine("Deleted item " + deletedObject.Key); } foreach (DeleteError deleteError in errorResponse.DeleteErrors) { Console.WriteLine("Error deleting item " + deleteError.Key); Console.WriteLine(" Code - " + deleteError.Code); Console.WriteLine(" Message - " + deleteError.Message); } } #endregion } { #region CopyObject Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request CopyObjectRequest request = new CopyObjectRequest { SourceBucket = "SampleBucket", SourceKey = "Item1", DestinationBucket = "AnotherBucket", DestinationKey = "Copy1", CannedACL = S3CannedACL.PublicRead }; // Issue request client.CopyObject(request); #endregion } { #region CopyObject Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request CopyObjectRequest request = new CopyObjectRequest { SourceBucket = "SampleBucket", SourceKey = "Item1", DestinationBucket = "AnotherBucket", DestinationKey = "Copy1", CannedACL = S3CannedACL.PublicRead }; // Issue request client.CopyObject(request); #endregion } { #region ListVersions Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Turn versioning on for a bucket client.PutBucketVersioning(new PutBucketVersioningRequest { BucketName = "SampleBucket", VersioningConfig = new S3BucketVersioningConfig { Status = "Enable" } }); // Populate bucket with multiple items, each with multiple versions PopulateBucket(client, "SampleBucket"); // Get versions ListVersionsRequest request = new ListVersionsRequest { BucketName = "SampleBucket" }; // Make paged ListVersions calls ListVersionsResponse response; do { response = client.ListVersions(request); // View information about versions foreach (var version in response.Versions) { Console.WriteLine("Key = {0}, Version = {1}, IsLatest = {2}, LastModified = {3}, Size = {4}", version.Key, version.VersionId, version.IsLatest, version.LastModified, version.Size); } request.KeyMarker = response.NextKeyMarker; request.VersionIdMarker = response.NextVersionIdMarker; } while (response.IsTruncated); #endregion } { #region Multipart Upload Sample int MB = (int)Math.Pow(2, 20); // Create a client AmazonS3Client client = new AmazonS3Client(); // Define input stream Stream inputStream = Create13MBDataStream(); // Initiate multipart upload InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest { BucketName = "SampleBucket", Key = "Item1" }; InitiateMultipartUploadResponse initResponse = client.InitiateMultipartUpload(initRequest); // Upload part 1 UploadPartRequest uploadRequest = new UploadPartRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartNumber = 1, PartSize = 5 * MB, InputStream = inputStream }; UploadPartResponse up1Response = client.UploadPart(uploadRequest); // Upload part 2 uploadRequest = new UploadPartRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartNumber = 2, PartSize = 5 * MB, InputStream = inputStream }; UploadPartResponse up2Response = client.UploadPart(uploadRequest); // Upload part 3 uploadRequest = new UploadPartRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartNumber = 3, InputStream = inputStream }; UploadPartResponse up3Response = client.UploadPart(uploadRequest); // List parts for current upload ListPartsRequest listPartRequest = new ListPartsRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId }; ListPartsResponse listPartResponse = client.ListParts(listPartRequest); Debug.Assert(listPartResponse.Parts.Count == 3); // Complete the multipart upload CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartETags = new List<PartETag> { new PartETag { ETag = up1Response.ETag, PartNumber = 1 }, new PartETag { ETag = up2Response.ETag, PartNumber = 2 }, new PartETag { ETag = up3Response.ETag, PartNumber = 3 } } }; CompleteMultipartUploadResponse compResponse = client.CompleteMultipartUpload(compRequest); #endregion } }