private void Publish(string stagingFolder, string fileName, string publishFolder, string bucketName) { fileName = System.IO.Path.GetFileName(fileName); CopyObjectRequest copyRequest = new CopyObjectRequest() { SourceBucket = bucketName, SourceKey = stagingFolder + "/" + fileName, DestinationBucket = bucketName, DestinationKey = publishFolder + "/" + fileName }; CopyObjectResponse result = _client.CopyObject(copyRequest); //TODO: inspect result. }
internal void RenameObject(String sourceKey, String destKey) { CopyObjectRequest request = new CopyObjectRequest() { CannedACL = S3CannedACL.PublicRead, DestinationBucket = _bucketName, DestinationKey = GetFullPrefix(destKey), MetadataDirective = S3MetadataDirective.COPY, SourceBucket = _bucketName, SourceKey = GetFullPrefix(sourceKey) }; S3ItemData destination = GetObject(destKey); if (destination != null) { throw new Exception(String.Format("Destination object with key {0} already exists.", request.DestinationKey)); } CopyObjectResponse response = _S3Client.CopyObject(request); if (response.HttpStatusCode != System.Net.HttpStatusCode.OK) { throw new Exception(String.Format("Failed to copy {0} to {1}", request.SourceKey, request.DestinationKey)); } _S3Client.Delete(_bucketName, request.SourceKey, null); }
/// <summary> /// Moves an image (well, any object, really) from one key to another /// </summary> /// <param name="szSrc">Source path (key)</param> /// <param name="szDst">Destination path (key)</param> public static void MoveImageOnS3(string szSrc, string szDst) { try { using (IAmazonS3 s3 = AWSConfiguration.S3Client()) { CopyObjectRequest cor = new CopyObjectRequest(); DeleteObjectRequest dor = new DeleteObjectRequest(); cor.SourceBucket = cor.DestinationBucket = dor.BucketName = AWSConfiguration.CurrentS3Bucket; cor.DestinationKey = szDst; cor.SourceKey = dor.Key = szSrc; cor.CannedACL = S3CannedACL.PublicRead; cor.StorageClass = S3StorageClass.Standard; // vs. reduced s3.CopyObject(cor); s3.DeleteObject(dor); } } catch (AmazonS3Exception ex) { util.NotifyAdminEvent("Error moving image on S3", String.Format(CultureInfo.InvariantCulture, "Error moving from key\r\n{0}to\r\n{1}\r\n\r\n{2}", szSrc, szDst, WrapAmazonS3Exception(ex)), ProfileRoles.maskSiteAdminOnly); throw new MyFlightbookException(String.Format(CultureInfo.InvariantCulture, "Error moving file on S3: Request address:{0}, Message:{1}", WrapAmazonS3Exception(ex), ex.Message)); } catch (Exception ex) { throw new MyFlightbookException("Unknown error moving image on S3: " + ex.Message); } }
public bool SaveFile(string contentType, string fullFileName, Stream mediaStream, bool updateMaster = true, bool updateWeb = true) { try { if (IscdnPropertyValid() && (updateMaster || updateWeb)) { using (mediaStream) { if (updateWeb) { using (IAmazonS3 client = this.CreateClient()) { var putObjectRequest = this.CreatePutObjectRequest(cdnPropertiesModel.S3BucketName, cdnHelper.GetCdnUrlOnDatabase(fullFileName, false), mediaStream, contentType); client.PutObject(putObjectRequest); } } //Copy the Item for Master from Web, if both are requested for Update if (updateMaster & updateWeb)//For Master Database { using (IAmazonS3 client = this.CreateClient()) { client.CopyObject(cdnPropertiesModel.S3BucketName, cdnHelper.GetCdnUrlOnDatabase(fullFileName, false), cdnPropertiesModel.S3BucketName, cdnHelper.GetCdnUrlOnDatabase(fullFileName, true)); } } else if (updateMaster) { using (IAmazonS3 client = this.CreateClient()) { var putObjectRequest = this.CreatePutObjectRequest(cdnPropertiesModel.S3BucketName, cdnHelper.GetCdnUrlOnDatabase(fullFileName, true), mediaStream, contentType, false); client.PutObject(putObjectRequest); } } } return(true); } else { Log.Info(cdnPropertiesModel == null ? "CdnPropertiy is Null" : "not null", this); } } catch (AmazonS3Exception ex) { Log.Error(Helper.Constants.Message.SaveFileS3Exception + ((object)ex).ToString(), typeof(AwsS3CdnServerHandler)); SheerResponse.ShowError((Exception)ex); } catch (StackOverflowException ex) { Log.Error(Helper.Constants.Message.SaveFileStackTraceException + ((object)ex).ToString(), typeof(AwsS3CdnServerHandler)); SheerResponse.ShowError((Exception)ex); } catch (Exception ex) { Log.Error(Helper.Constants.Message.SaveFileException + ex.ToString(), typeof(AwsS3CdnServerHandler)); SheerResponse.ShowError(ex); } return(false); }
public void CopyFolder(string sourceFolderPath, string targetFolderPath) { try { targetFolderPath = CorrectFolderPath(targetFolderPath); sourceFolderPath = CorrectFolderPath(sourceFolderPath); if (targetFolderPath == sourceFolderPath) { throw new ApplicationException("CopyFolder: target and source paths cannot be equal."); } // get entire contents of source folder ListObjectsRequest listRequest = new ListObjectsRequest() { BucketName = _bucketName, Prefix = sourceFolderPath }; ListObjectsResponse listResponse = _awsS3Client.ListObjects(listRequest); // create empty target folder CreateFolder(targetFolderPath); // copy contents of source to dest foreach (var sourceObject in listResponse.S3Objects) { CopyObjectRequest request = new CopyObjectRequest { SourceKey = sourceObject.Key, DestinationKey = sourceObject.Key.Replace(sourceFolderPath, targetFolderPath), SourceBucket = _bucketName, DestinationBucket = _bucketName, }; CopyObjectResponse response = _awsS3Client.CopyObject(request); } } catch (Exception ex) { throw new ApplicationException("S3 CopyFolder - unexpected exception.", ex); } }
private void RenameObject(string oldPath, string newPath, IAmazonS3 client) { CopyObjectRequest copyRequest = new CopyObjectRequest(); copyRequest.SourceBucket = BucketName; copyRequest.SourceKey = oldPath; copyRequest.DestinationBucket = BucketName; copyRequest.DestinationKey = newPath; copyRequest.CannedACL = S3CannedACL.PublicRead; client.CopyObject(copyRequest); }
public void SaveDataFile(byte[] data, bool branch, int toFileVersion, String stationName) { using (IAmazonS3 s3Client = CreateS3Client()) { TransferUtility fileTransferUtility = new TransferUtility(s3Client); if (branch) { //upload a branched copy, but do not update the main version var newFileName = AddPreSuffixToFileName($"{stationName}_{toFileVersion.ToString().PadLeft(4, '0')}", _dataFileName); var fileKey = $"{_secretsDirectory}/{newFileName}"; using (var ms = new MemoryStream(data)) { fileTransferUtility.Upload(ms, _bucketName, fileKey); } } else { //copy the current main to a new name propertyValue as a suffix then //upload a new copy var fileKey = $"{_secretsDirectory}/{_dataFileName}"; var response = s3Client.GetObjectMetadata(new GetObjectMetadataRequest() { BucketName = _bucketName, Key = fileKey }); var existingVersion = response.Metadata[$"x-amz-meta-{VersionIdPropertyName.ToLower()}"]; var oldFileKey = $"{_secretsDirectory}.old/{_dataFileName}.{existingVersion}"; s3Client.CopyObject(new CopyObjectRequest() { SourceBucket = _bucketName, DestinationBucket = _bucketName, SourceKey = fileKey, DestinationKey = oldFileKey }); using (var ms = new MemoryStream(data)) { var uploadRequest = new TransferUtilityUploadRequest() { BucketName = _bucketName, Key = fileKey, InputStream = ms }; uploadRequest.Metadata[VersionIdPropertyName] = toFileVersion.ToString(); fileTransferUtility.Upload(uploadRequest); } } } }
/// <summary> /// 移动文件 /// </summary> /// <param name="S3Manager"></param> /// <param name="bucketName1"></param> /// <param name="bucketName2"></param> /// <param name="fileName1"></param> /// <param name="fileName2"></param> /// <returns></returns> public static ActionResult Move(IAmazonS3 S3Manager, string bucketName1, string fileName1, string bucketName2, string fileName2) { ActionResult ar = new ActionResult() { IsSuccess = false, Msg = "Empty" }; if (S3Manager != null) { ListObjectsRequest request = new ListObjectsRequest(); request.BucketName = bucketName1; request.Prefix = fileName1; ListObjectsResponse response = S3Manager.ListObjects(request); if (response.S3Objects.Count == 1) { CopyObjectRequest copyObjectRequest = new CopyObjectRequest(); copyObjectRequest.SourceBucket = bucketName1; copyObjectRequest.SourceKey = fileName1; copyObjectRequest.DestinationBucket = bucketName2; copyObjectRequest.DestinationKey = fileName2; CopyObjectResponse res = S3Manager.CopyObject(copyObjectRequest); if (res.HttpStatusCode == HttpStatusCode.OK) { S3Manager.DeleteObject(bucketName1, fileName1); ar.IsSuccess = true; ar.Msg = "移动成功!"; } else { ar.IsSuccess = false; ar.Msg = "复制失败!"; } } else { ar.IsSuccess = false; ar.Msg = "文件不存在!"; } } return(ar); }
///// <summary> ///// Sets the redirect location for the S3 Object's when being accessed through the S3 website endpoint. ///// </summary> ///// <param name="s3Object">The S3 Object</param> ///// <param name="websiteRedirectLocation">The redirect location</param> ///// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> //public static void SetWebsiteRedirectLocation(S3Object s3Object, string websiteRedirectLocation, IAmazonS3 s3Client) //{ // SetWebsiteRedirectLocation(s3Object.BucketName, s3Object.Key, websiteRedirectLocation, s3Client); //} /// <summary> /// Sets the redirect location for the S3 Object's when being accessed through the S3 website endpoint. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object</param> /// <param name="websiteRedirectLocation">The redirect location</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> public static void SetWebsiteRedirectLocation(IAmazonS3 s3Client, string bucketName, string key, string websiteRedirectLocation) { CopyObjectRequest copyRequest; PutACLRequest putACLRequest; SetupForObjectModification(s3Client, bucketName, key, null, out copyRequest, out putACLRequest); copyRequest.WebsiteRedirectLocation = websiteRedirectLocation; CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); if (!string.IsNullOrEmpty(copyResponse.SourceVersionId)) { putACLRequest.VersionId = copyResponse.SourceVersionId; } s3Client.PutACL(putACLRequest); }
///// <summary> ///// Sets the server side encryption method for the S3 Object Version to the value ///// specified. ///// </summary> ///// <param name="s3ObjectVer">The S3 Object Version</param> ///// <param name="method">The server side encryption method</param> ///// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> //public static void SetServerSideEncryption(S3ObjectVersion s3ObjectVer, ServerSideEncryptionMethod method, IAmazonS3 s3Client) //{ // SetServerSideEncryption(s3ObjectVer.BucketName, s3ObjectVer.Key, s3ObjectVer.VersionId, method, s3Client); //} /// <summary> /// Sets the server side encryption method for the S3 Object's Version to the value /// specified. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object</param> /// <param name="version">The version of the S3 Object</param> /// <param name="method">The server side encryption method</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> public static void SetServerSideEncryption(IAmazonS3 s3Client, string bucketName, string key, string version, ServerSideEncryptionMethod method) { CopyObjectRequest copyRequest; PutACLRequest putACLRequest; SetupForObjectModification(s3Client, bucketName, key, version, out copyRequest, out putACLRequest); copyRequest.ServerSideEncryptionMethod = method; CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); if (!string.IsNullOrEmpty(copyResponse.SourceVersionId)) { putACLRequest.VersionId = copyResponse.SourceVersionId; } s3Client.PutACL(putACLRequest); }
/// <summary> /// Sets the storage class for the S3 Object's Version to the value /// specified. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object whose storage class needs changing</param> /// <param name="version">The version of the S3 Object whose storage class needs changing</param> /// <param name="sClass">The new Storage Class for the object</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> /// <seealso cref="T:Amazon.S3.S3StorageClass"/> public static void SetObjectStorageClass(IAmazonS3 s3Client, string bucketName, string key, string version, S3StorageClass sClass) { CopyObjectRequest copyRequest; PutACLRequest putACLRequest; SetupForObjectModification(s3Client, bucketName, key, version, out copyRequest, out putACLRequest); copyRequest.StorageClass = sClass; CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); if (!string.IsNullOrEmpty(copyResponse.SourceVersionId)) { putACLRequest.VersionId = copyResponse.SourceVersionId; } s3Client.PutACL(putACLRequest); }
/// <summary> /// Copies this file to the location indicated by the passed in S3FileInfo. /// If the file already exists in S3 and overwrite is set to false than an ArgumentException is thrown. /// </summary> /// <param name="file">The target location to copy this file to.</param> /// <param name="overwrite">Determines whether the file can be overwritten.</param> /// <exception cref="T:System.IO.IOException">If the file already exists in S3 and overwrite is set to false.</exception> /// <exception cref="T:System.Net.WebException"></exception> /// <exception cref="T:Amazon.S3.AmazonS3Exception"></exception> /// <returns>S3FileInfo of the newly copied file.</returns> public S3FileInfo CopyTo(S3FileInfo file, bool overwrite) { if (!overwrite) { if (file.Exists) { throw new IOException("File already exists"); } } if (SameClient(file)) { var request = new CopyObjectRequest { DestinationBucket = file.BucketName, DestinationKey = S3Helper.EncodeKey(file.ObjectKey), SourceBucket = bucket, SourceKey = S3Helper.EncodeKey(key) }; ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)request).AddBeforeRequestHandler(S3Helper.FileIORequestEventHandler); s3Client.CopyObject(request); } else { var getObjectRequest = new GetObjectRequest { BucketName = bucket, Key = S3Helper.EncodeKey(key) }; ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)getObjectRequest).AddBeforeRequestHandler(S3Helper.FileIORequestEventHandler); var getObjectResponse = s3Client.GetObject(getObjectRequest); using (Stream stream = getObjectResponse.ResponseStream) { var putObjectRequest = new PutObjectRequest { BucketName = file.BucketName, Key = S3Helper.EncodeKey(file.ObjectKey), InputStream = stream }; ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)putObjectRequest).AddBeforeRequestHandler(S3Helper.FileIORequestEventHandler); file.S3Client.PutObject(putObjectRequest); } } return(file); }
private void Recycle(IAmazonS3 client, string domain, string key) { if (string.IsNullOrEmpty(_recycleDir)) { return; } var copyObjectRequest = new CopyObjectRequest { SourceBucket = _bucket, SourceKey = key, DestinationBucket = _bucket, DestinationKey = GetRecyclePath(key), CannedACL = GetDomainACL(domain), MetadataDirective = S3MetadataDirective.REPLACE, ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256 }; client.CopyObject(copyObjectRequest); }
private static async Task CopyingObjectAsync() { try { CopyObjectRequest request = new CopyObjectRequest { SourceBucket = sourceBucket, SourceKey = objectKey, DestinationBucket = destinationBucket, DestinationKey = destObjectKey }; CopyObjectResponse response = s3Client.CopyObject(request); } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } }
public bool CopyAObject(string bucketname, string oldkeyname, string newkeyname) { try { // Create a CopyObject request CopyObjectRequest request = new CopyObjectRequest { SourceBucket = bucketname, SourceKey = oldkeyname, DestinationBucket = bucketname, DestinationKey = newkeyname, CannedACL = S3CannedACL.PublicRead }; // Issue request client.CopyObject(request); return(true); } catch (AmazonS3Exception amazonS3Exception) { string filename = ConfigurationManager.AppSettings["LogFile"]; using (StreamWriter writer = File.AppendText(filename)) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { log.WriteLog("Please check the provided AWS Credentials.", writer); log.WriteLog("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3", writer); return(false); } else { log.WriteLog("An Error, number " + amazonS3Exception.ErrorCode + ", occurred when copying a object with the message " + amazonS3Exception.Message, writer); return(false); } } } }
public static string CopyingObject( string sourceKey, string destinationKey ) { string bucketName = "media.cloud.glv.co.jp"; try { using (IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client( RegionEndpoint.APNortheast1 )) { CopyObjectRequest request = new CopyObjectRequest { SourceBucket = bucketName, SourceKey = sourceKey, DestinationBucket = bucketName, DestinationKey = destinationKey }; CopyObjectResponse response = client.CopyObject( request ); return destinationKey; } } catch (AmazonS3Exception) { return null; } }
private void Recycle(IAmazonS3 client, string domain, string key) { if (string.IsNullOrEmpty(_recycleDir)) return; var copyObjectRequest = new CopyObjectRequest { SourceBucket = _bucket, SourceKey = key, DestinationBucket = _bucket, DestinationKey = GetRecyclePath(key), CannedACL = GetDomainACL(domain), MetadataDirective = S3MetadataDirective.REPLACE, ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256 }; client.CopyObject(copyObjectRequest); }
///// <summary> ///// Sets the storage class for the S3 Object Version to the value ///// specified. ///// </summary> ///// <param name="s3ObjectVer">The S3 Object Version whose storage class needs changing</param> ///// <param name="sClass">The new Storage Class for the object</param> ///// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> ///// <seealso cref="T:Amazon.S3.Model.S3StorageClass"/> //public static void SetObjectStorageClass(S3ObjectVersion s3ObjectVer, S3StorageClass sClass, IAmazonS3 s3Client) //{ // SetObjectStorageClass(s3ObjectVer.BucketName, s3ObjectVer.Key, s3ObjectVer.VersionId, sClass, s3Client); //} /// <summary> /// Sets the storage class for the S3 Object's Version to the value /// specified. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object whose storage class needs changing</param> /// <param name="version">The version of the S3 Object whose storage class needs changing</param> /// <param name="sClass">The new Storage Class for the object</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> /// <seealso cref="T:Amazon.S3.Model.S3StorageClass"/> public static void SetObjectStorageClass(IAmazonS3 s3Client, string bucketName, string key, string version, S3StorageClass sClass) { CopyObjectRequest copyRequest; PutACLRequest putACLRequest; SetupForObjectModification(s3Client, bucketName, key, version, out copyRequest, out putACLRequest); copyRequest.StorageClass = sClass; CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); if (!string.IsNullOrEmpty(copyResponse.SourceVersionId)) putACLRequest.VersionId = copyResponse.SourceVersionId; s3Client.PutACL(putACLRequest); }
///// <summary> ///// Sets the server side encryption method for the S3 Object Version to the value ///// specified. ///// </summary> ///// <param name="s3ObjectVer">The S3 Object Version</param> ///// <param name="method">The server side encryption method</param> ///// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> //public static void SetServerSideEncryption(S3ObjectVersion s3ObjectVer, ServerSideEncryptionMethod method, IAmazonS3 s3Client) //{ // SetServerSideEncryption(s3ObjectVer.BucketName, s3ObjectVer.Key, s3ObjectVer.VersionId, method, s3Client); //} /// <summary> /// Sets the server side encryption method for the S3 Object's Version to the value /// specified. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object</param> /// <param name="version">The version of the S3 Object</param> /// <param name="method">The server side encryption method</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> public static void SetServerSideEncryption(IAmazonS3 s3Client, string bucketName, string key, string version, ServerSideEncryptionMethod method) { CopyObjectRequest copyRequest; PutACLRequest putACLRequest; SetupForObjectModification(s3Client, bucketName, key, version, out copyRequest, out putACLRequest); copyRequest.ServerSideEncryptionMethod = method; CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); if (!string.IsNullOrEmpty(copyResponse.SourceVersionId)) putACLRequest.VersionId = copyResponse.SourceVersionId; s3Client.PutACL(putACLRequest); }
///// <summary> ///// Sets the redirect location for the S3 Object's when being accessed through the S3 website endpoint. ///// </summary> ///// <param name="s3Object">The S3 Object</param> ///// <param name="websiteRedirectLocation">The redirect location</param> ///// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> //public static void SetWebsiteRedirectLocation(S3Object s3Object, string websiteRedirectLocation, IAmazonS3 s3Client) //{ // SetWebsiteRedirectLocation(s3Object.BucketName, s3Object.Key, websiteRedirectLocation, s3Client); //} /// <summary> /// Sets the redirect location for the S3 Object's when being accessed through the S3 website endpoint. /// </summary> /// <param name="bucketName">The name of the bucket in which the key is stored</param> /// <param name="key">The key of the S3 Object</param> /// <param name="websiteRedirectLocation">The redirect location</param> /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param> public static void SetWebsiteRedirectLocation(IAmazonS3 s3Client, string bucketName, string key, string websiteRedirectLocation) { CopyObjectRequest copyRequest; PutACLRequest putACLRequest; SetupForObjectModification(s3Client, bucketName, key, null, out copyRequest, out putACLRequest); copyRequest.WebsiteRedirectLocation = websiteRedirectLocation; CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest); if (!string.IsNullOrEmpty(copyResponse.SourceVersionId)) putACLRequest.VersionId = copyResponse.SourceVersionId; s3Client.PutACL(putACLRequest); }