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


C# AmazonS3Client.GetObject方法代码示例

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


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

示例1: Main

	static void Main()
	{
		// Connect to Amazon S3 service with authentication
		BasicAWSCredentials basicCredentials =
			new BasicAWSCredentials("AKIAIIYG27E27PLQ6EWQ", 
			"hr9+5JrS95zA5U9C6OmNji+ZOTR+w3vIXbWr3/td");
		AmazonS3Client s3Client = new AmazonS3Client(basicCredentials);

		// Display all S3 buckets
		ListBucketsResponse buckets = s3Client.ListBuckets();
		foreach (var bucket in buckets.Buckets)
		{
			Console.WriteLine(bucket.BucketName);
		}

		// Display and download the files in the first S3 bucket
		string bucketName = buckets.Buckets[0].BucketName;
		Console.WriteLine("Objects in bucket '{0}':", bucketName);
		ListObjectsResponse objects =
			s3Client.ListObjects(new ListObjectsRequest() { BucketName = bucketName });
		foreach (var s3Object in objects.S3Objects)
		{
			Console.WriteLine("\t{0} ({1})", s3Object.Key, s3Object.Size);
			if (s3Object.Size > 0)
			{
				// We have a file (not a directory) --> download it
				GetObjectResponse objData = s3Client.GetObject(
					new GetObjectRequest() { BucketName = bucketName, Key = s3Object.Key });
				string s3FileName = new FileInfo(s3Object.Key).Name;
				SaveStreamToFile(objData.ResponseStream, s3FileName);
			}
		}

		// Create a new directory and upload a file in it
		string path = "uploads/new_folder_" + DateTime.Now.Ticks;
		string newFileName = "example.txt";
		string fullFileName = path + "/" + newFileName;
		string fileContents = "This is an example file created through the Amazon S3 API.";
		s3Client.PutObject(new PutObjectRequest() { 
			BucketName = bucketName, 
			Key = fullFileName,
			ContentBody = fileContents}
		);
		Console.WriteLine("Created a file in Amazon S3: {0}", fullFileName);

		// Share the uploaded file and get a download URL
		string uploadedFileUrl = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
		{ 
			BucketName = bucketName,
			Key = fullFileName,
			Expires = DateTime.Now.AddYears(5)
		});
		Console.WriteLine("File download URL: {0}", uploadedFileUrl);
		System.Diagnostics.Process.Start(uploadedFileUrl);
	}
开发者ID:resnick1223,项目名称:Web-Services-and-Cloud,代码行数:55,代码来源:AmazonS3Example.cs

示例2: GetComputeNode

        public IComputeNode GetComputeNode()
        {
            IComputeNode compute_node = null;
            try
            {
                //amazon client
                using (var client = new AmazonS3Client())
                {
                    //download request
                    using (var response = client.GetObject(new GetObjectRequest()
                        .WithBucketName(AmazonBucket)
                        .WithKey(BermudaConfig)))
                    {
                        using (StreamReader reader = new StreamReader(response.ResponseStream))
                        {
                            //read the file
                            string data = reader.ReadToEnd();

                            //deserialize
                            compute_node = new ComputeNode().DeserializeComputeNode(data);
                            compute_node.Init(CurrentInstanceIndex, AllNodeEndpoints.Count());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            return compute_node;
        }
开发者ID:yonglehou,项目名称:Bermuda,代码行数:31,代码来源:AmazonHostEnvironmentConfiguration.cs

示例3: GetTargetAppVersion

 public Guid? GetTargetAppVersion(Guid targetKey, Guid appKey)
 {
     try
     {
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObject(new GetObjectRequest()
             {
                 BucketName = Context.BucketName,
                 Key = GetTargetAppVersionInfoPath(targetKey, appKey),
             }))
             {
                 using (var stream = res.ResponseStream)
                 {
                     return Utils.Serialisation.ParseKey(stream);
                 }
             }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return null;
         }
         else
         {
             throw new DeploymentException(string.Format("Failed getting version for app with key \"{0}\" and target with the key \"{1}\".", appKey, targetKey), awsEx);
         }
     }
 }
开发者ID:danielrbradley,项目名称:Plywood,代码行数:31,代码来源:TargetAppVersions.cs

示例4: Main

        static void Main(string[] args)
        {
            try
            {
                var client = new AmazonS3Client();

                PutObjectResponse putResponse = client.PutObject(new PutObjectRequest
                {
                    BucketName = BUCKET_NAME,
                    FilePath = TEST_FILE
                });

                GetObjectResponse getResponse = client.GetObject(new GetObjectRequest
                {
                    BucketName = BUCKET_NAME,
                    Key = TEST_FILE
                });

                getResponse.WriteResponseStreamToFile(@"c:\talk\" + TEST_FILE);


                var url = client.GetPreSignedURL(new GetPreSignedUrlRequest
                {
                    BucketName = BUCKET_NAME,
                    Key = TEST_FILE,
                    Expires = DateTime.Now.AddHours(1)
                });

                OpenURL(url);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
开发者ID:jamisliao,项目名称:aws-sdk-net-samples,代码行数:35,代码来源:Program.cs

示例5: GetComputeNode

        public IComputeNode GetComputeNode()
        {
            IComputeNode compute_node = null;
            try
            {
                //amazon client
                using (var client = new AmazonS3Client())
                {
                    //download request
                    using (var response = client.GetObject(new GetObjectRequest()
                        .WithBucketName(AmazonBucket)
                        .WithKey(BermudaConfig)))
                    {
                        using (StreamReader reader = new StreamReader(response.ResponseStream))
                        {
                            //read the file
                            string data = reader.ReadToEnd();

                            //deserialize
                            compute_node = new ComputeNode().DeserializeComputeNode(data);
                            if(compute_node.Catalogs.Values.Cast<ICatalog>().FirstOrDefault().CatalogMetadata.Tables.FirstOrDefault().Value.DataType == null)
                                compute_node.Catalogs.Values.Cast<ICatalog>().FirstOrDefault().CatalogMetadata.Tables.FirstOrDefault().Value.DataType = typeof(UDPTestDataItems);
                            compute_node.Init(CurrentInstanceIndex, AllNodeEndpoints.Count());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            return compute_node;
        }
开发者ID:yonglehou,项目名称:Bermuda,代码行数:33,代码来源:LocalHostEnvironmentConfiguration.cs

示例6: Main

 public static void Main(string[] args)
 {
     // Create a client
     AmazonS3Client client = new AmazonS3Client();
     string time = PutObj(client);
     // Create a GetObject request
     GetObjectRequest getObjRequest = new GetObjectRequest
     {
         BucketName = "com.loofah.photos",
         Key = time
     };
     System.Console.WriteLine(time);
     // Issue request and remember to dispose of the response
     using (GetObjectResponse getObjResponse = client.GetObject(getObjRequest))
     {
         getObjResponse.WriteResponseStreamToFile("C:\\Users\\Ryan\\Pictures\\" + time + ".jpg", false);
     }
     System.Console.Read();
 }
开发者ID:hkgumbs,项目名称:panes,代码行数:19,代码来源:List.xaml.cs

示例7: Setup

        // Sets up the student's input bucket with sample data files retrieved from the lab bucket.
        public static void Setup(AmazonS3Client s3ForStudentBuckets)
        {
            RegionEndpoint region = RegionEndpoint.USWest2;
            AmazonS3Client s3ForLabBucket;
            string textContent = null;
            bool exist = false;

            s3ForLabBucket = new AmazonS3Client(region);

            DataTransformer.CreateBucket(DataTransformer.InputBucketName);

            for (int i = 0; i < labBucketDataFileKeys.Length; i++)
            {
                GetObjectRequest requestForStream = new GetObjectRequest
                {
                    BucketName = labS3BucketName,
                    Key = labBucketDataFileKeys[i]
                };

                using (GetObjectResponse responseForStream = s3ForLabBucket.GetObject(requestForStream))
                {
                    using (StreamReader reader = new StreamReader(responseForStream.ResponseStream))
                    {
                        textContent = reader.ReadToEnd();

                        PutObjectRequest putRequest = new PutObjectRequest
                        {
                            BucketName = DataTransformer.InputBucketName,
                            Key = labBucketDataFileKeys[i].ToString().Split('/').Last(),
                            ContentBody = textContent
                        };

                        putRequest.Metadata.Add("ContentLength", responseForStream.ContentLength.ToString());
                        s3ForStudentBuckets.PutObject(putRequest);
                    }
                }
            }
        }
开发者ID:honux77,项目名称:aws-training-demo,代码行数:39,代码来源:Utils.cs

示例8: Run

        // methods
        public void Run(Object obj)
        {
            // counter for retires
            if (retry > 0)
            {

                // make the amazon client
                AmazonS3Client s3Client = new AmazonS3Client(awsKey, awsSecret, RegionEndpoint.GetBySystemName(region));

                try
                {

                    // request object with file
                    GetObjectRequest req = new GetObjectRequest();
                    req.BucketName = bucket;
                    req.Key = key;

                    // get the object from s3
                    GetObjectResponse res = s3Client.GetObject(req);

                    // test for paths in key name
                    if (file.IndexOf('/') > 0)
                    {
                        string filepath = file.Remove(file.LastIndexOf('/')).Replace('/', '\\');
                        if (!Directory.Exists(filepath))
                        {
                            Directory.CreateDirectory(filepath);
                        }
                    }

                    // establish a local file to send to
                    FileStream fs = File.Create(file.Replace('/', '\\'));

                    // transfer the stream to a file
                    byte[] buffer = new byte[8 * 1024];
                    int len;
                    while ((len = res.ResponseStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, len);
                    }

                    // close streams
                    res.ResponseStream.Close();
                    fs.Close();

                    // feedback
                    Console.WriteLine("File '" + key + "' in bucket '" + bucket + "' has been downloaded");

                }
                catch (Exception e)
                {

                    // output error
                    Console.WriteLine("Warning getting file '" + key + "' in bucket '" + bucket + "': " + e.Message + " (operation will be retried)");

                    // lower the counter and rerun
                    retry = retry - 1;
                    Run(obj);

                }

            }
            else
            {

                // exceeded retries, time to output error
                Console.WriteLine("Error adding file '" + file + "' in bucket '" + bucket + "'");

            }
        }
开发者ID:mmcquillan,项目名称:s3,代码行数:71,代码来源:s3Get.cs

示例9: ReadObjectData

        /// <summary>AWS S3 객체 읽어오기</summary>
        public Stream ReadObjectData(string pKey)
        {
            try
            {
                using (AmazonS3Client client = new AmazonS3Client())
                {
                    GetObjectRequest request = new GetObjectRequest
                    {
                        BucketName = strAwsBucketName,
                        Key = pKey
                    };

                    GetObjectResponse response = client.GetObject(request);

                    return response.ResponseStream;
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                throw amazonS3Exception;
            }
        }
开发者ID:chae87,项目名称:First,代码行数:23,代码来源:AwsCmm.cs

示例10: LoadIndex

 public EntityIndex LoadIndex(string path)
 {
     try
     {
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObject(new GetObjectRequest()
             {
                 BucketName = Context.BucketName,
                 Key = path,
             }))
             {
                 var index = new EntityIndex() { ETag = res.ETag };
                 using (var stream = res.ResponseStream)
                 {
                     index.Entries = ParseIndex(stream);
                 }
                 return index;
             }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return new EntityIndex() { Entries = new List<EntityIndexEntry>(), ETag = "" };
         }
         else
         {
             throw new DeploymentException("Failed loading group index", awsEx);
         }
     }
 }
开发者ID:danielrbradley,项目名称:Plywood,代码行数:33,代码来源:Indexes.cs

示例11: DownloadFiles

        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");
        }
开发者ID:BilliamBrown,项目名称:Chronos,代码行数:87,代码来源:S3.cs

示例12: DownloadClick

        private void DownloadClick(object sender, RoutedEventArgs e)
        {
            TaskDialogOptions o = new TaskDialogOptions
            {
                ShowMarqueeProgressBar = true,
                MainInstruction = "Press OK to download selected release... (MCLauncher will freeze! Do not close!)",
                MainIcon = VistaTaskDialogIcon.Information,
                EnableCallbackTimer = true,
                CustomButtons = new [] { "Cancel", "OK" }
            };
            string SecretKey = null;
            string PublicKey = null;
            Release Selected = (Release)JarList.SelectedItem;

            AmazonS3Client Client = new AmazonS3Client(PublicKey, SecretKey);

            GetObjectRequest Request = new GetObjectRequest
            {
                BucketName = "assets.minecraft.net",
                Key = Selected.Key
            };

            GetObjectResponse Result;
            TaskDialogResult tdr = TaskDialog.Show(o);
            if (tdr.CustomButtonResult == 0) return;
            Result = Client.GetObject(Request);
            Directory.CreateDirectory(Globals.LauncherDataPath + "/Minecraft/bin/");
            try
            {
                File.Copy(Globals.LauncherDataPath + "/Minecraft/bin/minecraft.jar", Globals.LauncherDataPath + "/Minecraft/OldMinecraft.jar", true);
                File.Delete(Globals.LauncherDataPath + "/Minecraft/bin/minecraft.jar");
            }
            catch (FileNotFoundException ex) { }
            Result.WriteResponseStreamToFile(Globals.LauncherDataPath + "/Minecraft/bin/minecraft.jar");
        }
开发者ID:tman0,项目名称:MCLauncher2,代码行数:35,代码来源:SnapshotDownloader.xaml.cs

示例13: Descarregar

        public ActionResult Descarregar(int Id)
        {
            Log.Info("Descarregar document " + Id);
            using (MySqlConnection connection = new MySqlConnection(ConnectionString))
            {
                MySqlCommand cmd = new MySqlCommand("SELECT Nom, MimeType, KeyAmazon FROM Documents WHERE Id = @Id", connection);
                cmd.Parameters.AddWithValue("@Id", Id);

                connection.Open();
                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    string Nom = reader.GetString(reader.GetOrdinal("Nom"));
                    string MimeType = reader.GetString(reader.GetOrdinal("MimeType"));
                    string KeyAmazon = reader.GetString(reader.GetOrdinal("KeyAmazon"));

                    using (IAmazonS3 client = new AmazonS3Client(AmazonEndPoint))
                    {
                        GetObjectRequest getRequest = new GetObjectRequest();
                        getRequest.BucketName = "hotnotes";
                        getRequest.Key = KeyAmazon;

                        using (GetObjectResponse response = client.GetObject(getRequest))
                        {
                            MemoryStream ms = new MemoryStream();
                            response.ResponseStream.CopyTo(ms);

                            char[] separator = new char[1];
                            separator[0] = '.';
                            string[] parts = response.Key.Split(separator);
                            string extensio = parts[parts.Length - 1];

                            return File(ms.ToArray(), MimeType, Nom + "." + extensio);
                        }
                    }
                }
            }
            return View();
        }
开发者ID:johnny32,项目名称:hotnotes,代码行数:40,代码来源:DocumentController.cs

示例14: PullVersion

        public void PullVersion(Guid key, DirectoryInfo directory, bool mergeExistingFiles = false)
        {
            if (!directory.Exists)
                throw new ArgumentException("Directory must exist.", "directory");
            if (!VersionExists(key))
                throw new VersionNotFoundException(string.Format("Could not find the version with key: {0}", key));
            if (!mergeExistingFiles)
            {
                if (directory.EnumerateFileSystemInfos().Any())
                    throw new ArgumentException("Target directory is not empty.");
            }

            try
            {
                var ignorePaths = new string[1] { ".info" };
                using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
                {
                    bool more = true;
                    string lastResult = null;
                    string prefix = string.Format("{0}/{1}/", STR_VERSIONS_CONTAINER_PATH, key.ToString("N"));
                    while (more)
                    {
                        using (var listResponse = client.ListObjects(new ListObjectsRequest()
                        {
                            BucketName = Context.BucketName,
                            Prefix = prefix,
                            Delimiter = lastResult,
                        }))
                        {
                            listResponse.S3Objects.Where(obj => !ignorePaths.Any(ignore => obj.Key == String.Format("{0}{1}", prefix, ignore)))
                                .AsParallel().ForAll(s3obj =>
                                {
                                    using (var getResponse = client.GetObject(new GetObjectRequest()
                                    {
                                        BucketName = Context.BucketName,
                                        Key = s3obj.Key,
                                    }))
                                    {
                                        getResponse.WriteResponseStreamToFile(Utils.Files.GetLocalAbsolutePath(s3obj.Key, prefix, directory.FullName));
                                    }
                                });
                            if (listResponse.IsTruncated)
                            {
                                more = true;
                            }
                            more = listResponse.IsTruncated;
                            lastResult = listResponse.S3Objects.Last().Key;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new DeploymentException(string.Format("Failed pushing to version with key \"{0}\"", key), ex);
            }
        }
开发者ID:danielrbradley,项目名称:Plywood,代码行数:56,代码来源:Versions.cs

示例15: GetFile

        public static GetObjectResponse GetFile(AwsCommonParams commonParams,
            string bucketName, string filePath)
        {
            // We need to strip off any leading '/' in the path or
            // else it creates a path with an empty leading segment
            // This also implements behavior consistent with the
            // edit counterpart routine for verification purposes
            if (filePath.StartsWith("/"))
                filePath = filePath.Substring(1);

            using (var s3 = new Amazon.S3.AmazonS3Client(
                commonParams.ResolveCredentials(),
                commonParams.RegionEndpoint))
            {
                var s3Requ = new Amazon.S3.Model.GetObjectRequest
                {
                    BucketName = bucketName,
                    //Prefix = filePath,
                    Key = filePath,
                };

                //var s3Resp = s3.ListObjects(s3Requ);
                try
                {
                    var s3Resp = s3.GetObject(s3Requ);

                    return s3Resp;
                }
                catch (AmazonS3Exception ex)
                    when (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }
            }
        }
开发者ID:bseddon,项目名称:ACMESharp,代码行数:35,代码来源:AwsS3ChallengeHandler.cs


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