如何在C#中使用AWSSDK.S3解析AWS S3路径(s3:// <存储桶名称> / <密钥>)以获取存储桶名称和密钥

时间:2019-06-06 14:30:36

标签: c# amazon-s3 aws-sdk

我有一个s3路径=> s3:// [存储桶名称] / [密钥]

s3://bn-complete-dev-test/1234567890/renders/Irradiance_A.png 

我需要分别获取bucket_name和密钥:

var s3PathParsed = parseS3Path("s3://bn-complete-dev-test/1234567890/renders/Irradiance_A.png");

s3PathParsed.BucketName == "bn-complete-dev-test"
s3PathParsed.Key == "1234567890/renders/Irradiance_A.png"

如何使用AWS开发工具包以正确的方式解析

1)我正在手动解析(使用正则表达式),工作正常,但我不舒服

public class S3Path : IS3Path
{
    private const string _s3PathRegex = @"[s|S]3:\/\/(?<bucket>[^\/]*)\/(?<key>.*)";

    public S3Path(string s3Path)
    {
        Path = s3Path;

        var rx = new Regex(_s3PathRegex).Match(s3Path);

        if (!rx.Success || rx.Groups.Count != 3)
            throw new Exception($"the S3 Path '{s3Path}' is wrong.");

        BucketName = rx.Groups[1].Value;
        Key = rx.Groups[2].Value;
    }

    public string Path { get; }

    public string BucketName { get; }

    public string Key { get; }
}

2)我使用了AWWSDK.S3的AmazonS3Uri:

string GetBucketNameFromS3Uri(string s3Uri)
{
    return new AmazonS3Uri(s3Uri).Bucket;            
}

我调用了该方法:

GetBucketNameFromS3Uri("s3://sunsite-complete-dev-test/1234567890/renders/Irradiance_A.png");

我有以下错误:

System.ArgumentException:'无效的S3 URI-主机名似乎不是有效的S3端点'

3)我也尝试

string GetBucketNameFromS3Uri(string s3Uri)
{
    return new AmazonS3Uri(new Uri(s3Uri)).Bucket;            
}

,具有相同的错误。

我在AWS论坛中创建了一个新线程,问题如下:https://forums.aws.amazon.com/thread.jspa?threadID=304401

7 个答案:

答案 0 :(得分:6)

在Java中,我们可以做类似

的操作
AmazonS3URI s3URI = new AmazonS3URI("s3://bucket/folder/object.csv");
S3Object s3Object = s3Client.getObject(s3URI.getBucket(), s3URI.getKey());

答案 1 :(得分:3)

如果您有对象URL(String...),则可以使用AmazonS3Uri

https://bn-complete-dev-test.s3.eu-west-2.amazonaws.com/1234567890/renders/Irradiance_A.pnlet

如果您有S3 URI(// using Amazon.S3.Util var uri = new AmazonS3Uri(urlString); var bucketName = uri.Bucket; var key = uri.Key; ),则涉及的内容会更多:

s3://bn-complete-dev-test/1234567890/renders/Irradiance_A.png

这是F#版本:

using System;

public static class S3
{
    public static Tuple<string, string> TryParseS3Uri(string x)
    {
        try
        {
            var uri = new Uri(x);

            if (uri.Scheme == "s3")
            {
                var bucket = uri.Host;
                var key = uri.LocalPath.Substring(1);

                return new Tuple<string, string>(bucket, key);
            }

            return null;
        }
        catch (Exception ex)
        {
            var ex2 = ex as UriFormatException;

            if (ex2 == null)
            {
                throw ex;
            }

            return null;
        }
    }
}

答案 2 :(得分:0)

我相信此正则表达式将为您提供您想要的东西:

viewGroup.setClipChildren(false);
viewGroup.setClipToPadding(false);

bucketname是S3路径的第一部分,密钥是第一个正斜杠之后的所有内容。

答案 3 :(得分:0)

AWSSDK.S3没有路径解析器,我们需要手动解析。您可以使用以下运行良好的类:

public class S3Path 
{
    private const string _s3PathRegex = @"[s|S]3:\/\/(?<bucket>[^\/]+)\/(?<key>.+)";

    public S3Path(string s3Path)
    {
        Path = s3Path;

        var rx = new Regex(_s3PathRegex).Match(s3Path);

        if (!rx.Success)
            throw new Exception($"the S3 Path '{s3Path}' is wrong.");

        BucketName = rx.Groups["bucket"].Value;
        Key = rx.Groups["key"].Value;
    }

    public string Path { get; }

    public string BucketName { get; }

    public string Key { get; }
}

I created a thread in AWS Forum报告缺少的功能。

答案 4 :(得分:0)

这是regex的scala版本和用法。

val regex = "s3a://([^/]*)/(.*)".r
val regex(bucketName, key) = "s3a://my-bucket-name/myrootpath/mychildpath/file.json"

println(bucketName) // my-bucket-name
println(key)        // myrootpath/mychildpath/file.json

答案 5 :(得分:0)

对于Javascript版本,您可以使用amazon-s3-uri

const AmazonS3URI = require('amazon-s3-uri')
 
try {
  const uri = 'https://bucket.s3-aws-region.amazonaws.com/key'
  const { region, bucket, key } = AmazonS3URI(uri)
} catch((err) => {
  console.warn(`${uri} is not a valid S3 uri`) // should not happen because `uri` is valid in that example
})

答案 6 :(得分:0)

AWSSDK.S3 Nuget 库有一个实用方法:

if (!Amazon.S3.Util.AmazonS3Uri.TryParseAmazonS3Uri(s3Url, out AmazonS3Uri amazonS3Uri))
  throw new ArgumentOutOfRangeException();
var bucket = amazonS3Uri.Bucket;
var key = amazonS3Uri.Key;
var region = amazonS3Uri.Region;