master
ZGGSONG 3 years ago
commit 14f22503c9

388
.gitignore vendored

@ -0,0 +1,388 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Nuget personal access tokens and Credentials
nuget.config
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
.idea/
*.sln.iml

@ -0,0 +1,9 @@
# Introduction
AWS S3对象存储案例
> .net NgGet先下载 `AWSSDK.S3`
- [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Config.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Config.html)
- [https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/dotnetv3/S3/UploadFileMPUHighLevelAPIExample/UploadFileMPUHighLevelAPIExample/UploadFileMPUHighLevelAPI.cs](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/dotnetv3/S3/UploadFileMPUHighLevelAPIExample/UploadFileMPUHighLevelAPIExample/UploadFileMPUHighLevelAPI.cs)
- [https://blog.csdn.net/tw_tangliang/article/details/118669099](https://blog.csdn.net/tw_tangliang/article/details/118669099)

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31702.278
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "S3Demo", "S3Demo\S3Demo.csproj", "{10785A7F-B71E-4576-BD28-3979CD9A005C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{10785A7F-B71E-4576-BD28-3979CD9A005C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{10785A7F-B71E-4576-BD28-3979CD9A005C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{10785A7F-B71E-4576-BD28-3979CD9A005C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{10785A7F-B71E-4576-BD28-3979CD9A005C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C17D23BC-A9C3-444C-9B4E-D1182D5DA1E7}
EndGlobalSection
EndGlobal

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

@ -0,0 +1,85 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace S3Demo
{
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
/// <summary>
/// This example shows how to use the Amazon Simple Storage System
/// (Amazon S3) client to copy an object from an Amazon S3 bucket to
/// another location such as your local system. The code uses the AWS
/// SDK for .NET version 3.7 and .NET Core 5.0.
/// </summary>
class GetObject
{
public static async Task Readobjectdata(string bucketName, string keyName, BasicAWSCredentials credentials, AmazonS3Config conf)
{
//const string bucketName = "doc-example-bucket";
//const string keyName = "filetodownload";
// If the Amazon Region where the S3 bucket was created is not
// the same as the region defined for the default user, specify
// the region as a parameter to the client constructor.
// For example: RegionEndpoint.USWest2;
IAmazonS3 client = new AmazonS3Client(credentials, conf);
await ReadObjectDataAsync(client, bucketName, keyName);
}
/// <summary>
/// This method copies the contents of the object keyName to another
/// location, for example, to your local system.
/// </summary>
/// <param name="client">The initialize S3 client used to call
/// GetObjectAsync.</param>
/// <param name="bucketName">The name of the S3 bucket which contains
/// the object to copy.</param>
/// <param name="keyName">The name of the object you want to copy.</param>
static async Task ReadObjectDataAsync(IAmazonS3 client, string bucketName, string keyName)
{
string responseBody = string.Empty;
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = keyName,
};
using (GetObjectResponse response = await client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
// Assume you have "title" as medata added to the object.
string title = response.Metadata["x-amz-meta-title"];
string contentType = response.Headers["Content-Type"];
int tag = response.TagCount;
foreach (var item in response.Key)
{
Console.WriteLine($"Object tag: {item}");
}
Console.WriteLine($"Object metadata, Title: {title}");
Console.WriteLine($"Content type: {contentType}");
// Retrieve the contents of the file.
responseBody = reader.ReadToEnd();
// Write the contents of the file to disk.
string filePath = $"C:\\Temp\\copy_of_{keyName}";
}
}
catch (AmazonS3Exception e)
{
// If the bucket or the object do not exist
Console.WriteLine($"Error: '{e.Message}'");
}
}
}
}

@ -0,0 +1,116 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace S3Demo
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
/// <summary>
/// This example shows how to work with tags in Amazon Simple Storage
/// System (Amazon S3) objects. The example was created using the AWS SDK
/// for .NET version 3.7 and .NET Core 5.0.
/// </summary>
public class ObjectTag
{
public static async Task Putobjectswithtags(string bucketName, string keyName, string filePath, string[] tags, BasicAWSCredentials credentials, AmazonS3Config conf)
{
//string bucketName = "doc-example-bucket";
//string keyName = "newobject.txt";
//string filePath = @"*** file path ***";
// Specify your bucket region (an example region is shown).
//RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
var client = new AmazonS3Client(credentials, conf);
await PutObjectsWithTagsAsync(client, bucketName, keyName, filePath, tags);
}
/// <summary>
/// This method uploads an object with tags. It then shows the tag
/// values, changes the tags, and shows the new tags.
/// </summary>
/// <param name="client">The Initialized Amazon S3 client object used
/// to call the methods to create and change an objects tags.</param>
/// <param name="bucketName">A string representing the name of the
/// bucket where the object will be stored.</param>
/// <param name="keyName">A string representing the key name of the
/// object to be tagged.</param>
/// <param name="filePath">The directory location and file name of the
/// object to be uploaded to the S3 bucket.</param>
public static async Task PutObjectsWithTagsAsync(IAmazonS3 client, string bucketName, string keyName, string filePath, string[] tags)
{
try
{
// Create an object with tags.
var putRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
TagSet = new List<Tag>
{
new Tag { Key = "sn", Value = tags[0] },
new Tag { Key = "date", Value = tags[1] },
new Tag { Key = "code", Value = tags[2] }
},
};
PutObjectResponse response = await client.PutObjectAsync(putRequest);
// Now retrieve the new object's tags.
GetObjectTaggingRequest getTagsRequest = new()
{
BucketName = bucketName,
Key = keyName,
};
GetObjectTaggingResponse objectTags = await client.GetObjectTaggingAsync(getTagsRequest);
// Display the tag values.
objectTags.Tagging
.ForEach(t => Console.WriteLine($"Key: {t.Key}, Value: {t.Value}"));
/*
// Replace the tagset new tags.
Tagging newTagSet = new()
{
TagSet = new List<Tag>
{
new Tag { Key = "Key3", Value = "Value3" },
new Tag { Key = "Key4", Value = "Value4" },
},
};
PutObjectTaggingRequest putObjTagsRequest = new()
{
BucketName = bucketName,
Key = keyName,
Tagging = newTagSet,
};
PutObjectTaggingResponse response2 = await client.PutObjectTaggingAsync(putObjTagsRequest);
// Retrieve the tags again and show the values.
GetObjectTaggingRequest getTagsRequest2 = new()
{
BucketName = bucketName,
Key = keyName,
};
GetObjectTaggingResponse objectTags2 = await client.GetObjectTaggingAsync(getTagsRequest2);
objectTags2.Tagging
.ForEach(t => Console.WriteLine($"Key: {t.Key}, Value: {t.Value}"));*/
}
catch (AmazonS3Exception ex)
{
Console.WriteLine(
$"Error: '{ex.Message}'");
}
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("S3Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("S3Demo")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("10785a7f-b71e-4576-bd28-3979cd9a005c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,55 @@
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using System;
using System.Threading.Tasks;
namespace S3Demo
{
public class Run
{
private static BasicAWSCredentials credentials = new BasicAWSCredentials("admin", "admin123.");
private static string bucketName = "minio/test";
/// <summary>
/// https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Config.html
/// https://blog.csdn.net/tw_tangliang/article/details/118669099
/// https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/dotnetv3/S3/UploadFileMPUHighLevelAPIExample/UploadFileMPUHighLevelAPIExample/UploadFileMPUHighLevelAPI.cs
/// </summary>
private static AmazonS3Config conf = new AmazonS3Config()
{
UseHttp = true,
ProxyHost = "http://192.168.60.132",
ProxyPort = 9000,
RegionEndpoint = RegionEndpoint.USEast1
};
public static async Task Main()
{
try
{
//uploaddir
string dirPath = @"C:\Users\song\Pictures\Saved Pictures\";
string suffix = "*.png";
//await UploadDirMPUHighLevelAPI.Uploaderdir(bucketName, dirPath, suffix, credentials, conf);
//uploadfile
string keyName = "360.png";
//await UploadFileMPUHighLevelAPI.Uploaderfile(bucketName, keyName, dirPath, credentials, conf);
//objectTag
string filaPath = @"C:\Users\song\Pictures\Saved Pictures\" + keyName;
String[] tags = new String[] { "SN123456", DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:sszzz"), "AB023" };
await ObjectTag.Putobjectswithtags(bucketName, keyName, filaPath, tags, credentials, conf);
//getObject
//await GetObject.Readobjectdata(bucketName, keyName, credentials, conf);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{10785A7F-B71E-4576-BD28-3979CD9A005C}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>S3Demo</RootNamespace>
<AssemblyName>S3Demo</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="AWSSDK.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604, processorArchitecture=MSIL">
<HintPath>..\packages\AWSSDK.Core.3.7.5.2\lib\net45\AWSSDK.Core.dll</HintPath>
</Reference>
<Reference Include="AWSSDK.S3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604, processorArchitecture=MSIL">
<HintPath>..\packages\AWSSDK.S3.3.7.5\lib\net45\AWSSDK.S3.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="GetObject.cs" />
<Compile Include="ObjectTag.cs" />
<Compile Include="Run.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UploadDirMPUHighLevelAPI.cs" />
<Compile Include="UploadFileMPUHighLevelAPI.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\AWSSDK.S3.3.7.5\analyzers\dotnet\cs\AWSSDK.S3.CodeAnalysis.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,98 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Transfer;
namespace S3Demo
{
/// <summary>
/// This example uses the Amazon Simple Storage Service (Amazon S3)
/// TransferUtility to copy an entire local directory to an Amazon S3
/// bucket. The example was created using the AWS SDK for .NET version
/// 3.7 and .NET Core 5.0.
/// </summary>
public class UploadDirMPUHighLevelAPI
{
public static async Task Uploaderdir(string existingBucketName, string directoryPath, string wildCard, BasicAWSCredentials credentials, AmazonS3Config conf)
{
//string existingBucketName = "doc-example-bucket";
//string directoryPath = @"directory_to_upload\";
// The example uploads only .txt files.
//string wildCard = "*.txt";
// If the AWS Region defined for your default user is different
// from the Region where your Amazon S3 bucket is located,
// pass the Region name to the S3 client object's constructor.
// For example: RegionEndpoint.USWest2 or RegionEndpoint.USEast2.
IAmazonS3 client = new AmazonS3Client(credentials, conf);
await UploadDirAsync(client, existingBucketName, directoryPath, wildCard);
}
/// <summary>
/// Uses an S3 multi-part transfer to upload all of the text files in
/// a local directory to an S3 bucket.
/// </summary>
/// <param name="client">The initialized S3 client object used to
/// perform the multi-part upload.</param>
/// <param name="bucketName">The name of the bucket to which the files
/// will be uploaded from the local directory.</param>
/// <param name="directoryPath">The path of the local directory that
/// contains the files to upload to the S3 bucket.</param>
/// <param name="wildCard">The wild card used to filter the files to
/// be uploaded.</param>
private static async Task UploadDirAsync(
IAmazonS3 client,
string bucketName,
string directoryPath,
string wildCard)
{
try
{
var directoryTransferUtility =
new TransferUtility(client);
// Upload the entire contents of a local directory to an S3
// bucket.
await directoryTransferUtility.UploadDirectoryAsync(
directoryPath,
bucketName);
Console.WriteLine("Upload statement 1 completed");
// Upload only the "wildCard" type files from a local directory using a
// recursive search to find text files in child directories.
await directoryTransferUtility.UploadDirectoryAsync(
directoryPath,
bucketName,
wildCard,
SearchOption.AllDirectories);
Console.WriteLine("Upload statement 2 completed");
// Performs the same as before using the
// TransferUtilityUploadDirectoryRequest instead of individual
// parameters.
var request = new TransferUtilityUploadDirectoryRequest
{
BucketName = bucketName,
Directory = directoryPath,
SearchOption = SearchOption.AllDirectories,
SearchPattern = wildCard,
};
await directoryTransferUtility.UploadDirectoryAsync(request);
Console.WriteLine("Upload statement 3 completed");
}
catch (AmazonS3Exception ex)
{
Console.WriteLine(
$"Error: {ex.Message}");
}
}
}
}

@ -0,0 +1,102 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Transfer;
namespace S3Demo
{
/// <summary>
/// This example shows how to use the TransferUtility api for Amazon Simple
/// Storage Service (Amazon S3) to upload a single file to an Amazon S3
/// bucket. The example was created using the AWS SDK for .NET version 3.7
/// and .NET Core 5.0.
/// </summary>
public class UploadFileMPUHighLevelAPI
{
public static async Task Uploaderfile(string bucketName, string keyName, string path, BasicAWSCredentials credentials, AmazonS3Config conf)
{
//string bucketName = "doc-example-bucket";
//string keyName = "sample_pic.png";
//string path = "filepath/directory/";
string filePath = $"{path}{keyName}";
// If the AWS Region defined for your default user is different
// from the Region where your Amazon S3 bucket is located,
// pass the Region name to the S3 client object's constructor.
// For example: RegionEndpoint.USWest2 or RegionEndpoint.USEast2.
IAmazonS3 client = new AmazonS3Client(credentials, conf);
await UploadFileAsync(client, bucketName, keyName, filePath);
}
/// <summary>
/// This method uploads a file to an S3 bucket using a TransferUtility
/// object.
/// </summary>
/// <param name="client">The initialized S3 client object used to
/// perform the multi-part upload.</param>
/// <param name="bucketName">The name of the bucket to which to upload
/// the file.</param>
/// <param name="keyName">The file name to be used in the
/// destination S3 bucket.</param>
/// <param name="filePath">The path, including the file name of the
/// file to be uploaded to the S3 bucket.</param>
private static async Task UploadFileAsync(
IAmazonS3 client,
string bucketName,
string keyName,
string filePath)
{
try
{
var fileTransferUtility =
new TransferUtility(client);
// Upload a file. The file name is used as the object key name.
await fileTransferUtility.UploadAsync(filePath, bucketName);
Console.WriteLine("Upload 1 completed");
// Specify object key name explicitly.
await fileTransferUtility.UploadAsync(filePath, bucketName, keyName);
Console.WriteLine("Upload 2 completed");
// Upload data from a System.IO.Stream object.
using (var fileToUpload =
new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
await fileTransferUtility.UploadAsync(
fileToUpload,
bucketName,
keyName);
}
Console.WriteLine("Upload 3 completed");
// Option 4. Specify advanced settings.
var fileTransferUtilityRequest = new TransferUtilityUploadRequest
{
BucketName = bucketName,
FilePath = filePath,
StorageClass = S3StorageClass.StandardInfrequentAccess,
PartSize = 6291456, // 6 MB.
Key = keyName,
CannedACL = S3CannedACL.PublicRead,
};
fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
await fileTransferUtility.UploadAsync(fileTransferUtilityRequest);
Console.WriteLine("Upload 4 completed");
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AWSSDK.Core" version="3.7.5.2" targetFramework="net45" />
<package id="AWSSDK.S3" version="3.7.5" targetFramework="net45" />
</packages>
Loading…
Cancel
Save