Download Objects from S3 Bucket using c# - c#

Im trying to download object from S3 bucket facing below issue
The Security token included in the request is Invalid .
Please check and correct where is the mistake.
Below is my code
1. Get Temporary credentails:
main()
{
string path = "http://XXX.XXX.XXX./latest/meta-data/iam/security-credentials/EC2_WLMA_Permissions";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
request.Method = "GET";
request.ContentType = "application/json";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
dynamic metaData = JsonConvert.DeserializeObject(result);
_awsAccessKeyId = metaData.AccessKeyId;
_awsSecretAccessKey = metaData.SecretAccessKey;
}
}
Create SessionAWSCredentials instance:
SessionAWSCredentials tempCredentials =
GetTemporaryCredentials(_awsAccessKeyId, _awsSecretAccessKey);
//GetTemporaryCredentials method:
private static SessionAWSCredentials GetTemporaryCredentials(
string accessKeyId, string secretAccessKeyId)
{
AmazonSecurityTokenServiceClient stsClient =
new AmazonSecurityTokenServiceClient(accessKeyId,
secretAccessKeyId);
Console.WriteLine(stsClient.ToString());
GetSessionTokenRequest getSessionTokenRequest =
new GetSessionTokenRequest();
getSessionTokenRequest.DurationSeconds = 7200; // seconds
GetSessionTokenResponse sessionTokenResponse =
stsClient.GetSessionToken(getSessionTokenRequest);
Console.WriteLine(sessionTokenResponse.ToString());
Credentials credentials = sessionTokenResponse.Credentials;
Console.WriteLine(credentials.ToString());
SessionAWSCredentials sessionCredentials =
new SessionAWSCredentials(credentials.AccessKeyId,
credentials.SecretAccessKey,
credentials.SessionToken);
return sessionCredentials;
}
Get files from S3 using AmazonS3Client:
using (IAmazonS3 client = new AmazonS3Client(tempCredentials,RegionEndpoint.USEast1))
{
GetObjectRequest request = new GetObjectRequest();
request.BucketName = "bucketName" + #"/" + "foldername";
request.Key = "Terms.docx";
GetObjectResponse response = client.GetObject(request);
response.WriteResponseStreamToFile("C:\\MyFile.docx");
}

We do something a little simpler for interfacing with S3 (downloads and uploads)
It looks like you went the more complex approach. You should try just using the TransferUtility instead:
TransferUtility fileTransferUtility =
new TransferUtility(
new AmazonS3Client("ACCESS-KEY-ID", "SECRET-ACCESS-KEY", Amazon.RegionEndpoint.CACentral1));
// Note the 'fileName' is the 'key' of the object in S3 (which is usually just the file name)
fileTransferUtility.Download(filePath, "my-bucket-name", fileName);
NOTE: TransferUtility.Download() returns void because it downloads the file to the path specified in the filePath argument. This may be a little different than what you were expecting but you can still open a FileStream to that path afterwards and manipulate the file all you want. For example:
using (FileStream fileDownloaded = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Do stuff with our newly downloaded file
}

Bucketname, Accesskey and secretkey, I took from web config. You could type manually.
public void DownloadObject(string imagename)
{
RegionEndpoint bucketRegion = RegionEndpoint.USEast1;
IAmazonS3 client = new AmazonS3Client(bucketRegion);
string accessKey = System.Configuration.ConfigurationManager.AppSettings["AWSAccessKey"];
string secretKey = System.Configuration.ConfigurationManager.AppSettings["AWSSecretKey"];
AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey), Amazon.RegionEndpoint.USEast1);
string objectKey = "EMR" + "/" + imagename;
//EMR is folder name of the image inside the bucket
GetObjectRequest request = new GetObjectRequest();
request.BucketName = System.Configuration.ConfigurationManager.AppSettings["bucketname"];
request.Key = objectKey;
GetObjectResponse response = s3Client.GetObject(request);
response.WriteResponseStreamToFile("D:\\Test\\"+ imagename);
}
//> D:\Test\ is local file path.

Following is how I download it. I need to download only .zip files in this case. Restricting to only required file types (.zip in my case), helped me to avoid errors related to (416) Requested Range Not Satisfiable
public static class MyAWS_S3_Helper
{
static string _S3Key = System.Configuration.ConfigurationManager.ConnectionStrings["S3BucketKey"].ConnectionString;
static string _S3SecretKey = System.Configuration.ConfigurationManager.ConnectionStrings["S3BucketSecretKey"].ConnectionString;
public static void S3Download(string bucketName, string _ObjectKey, string downloadPath)
{
IAmazonS3 _client = new AmazonS3Client(_S3Key, _S3SecretKey, Amazon.RegionEndpoint.USEast1);
TransferUtility fileTransferUtility = new TransferUtility(_client);
fileTransferUtility.Download(downloadPath + "\\" + _ObjectKey, bucketName, _ObjectKey);
_client.Dispose();
}
public static async Task AsyncDownload(string bucketName, string downloadPath, string requiredSunFolder)
{
var bucketRegion = RegionEndpoint.USEast1; //Change it
var credentials = new BasicAWSCredentials(_S3Key, _S3SecretKey);
var client = new AmazonS3Client(credentials, bucketRegion);
var request = new ListObjectsV2Request
{
BucketName = bucketName,
MaxKeys = 1000
};
var response = await client.ListObjectsV2Async(request);
var utility = new TransferUtility(client);
foreach (var obj in response.S3Objects)
{
string currentKey = obj.Key;
double sizeCheck = Convert.ToDouble(obj.Size);
int fileNameLength = currentKey.Length;
Console.WriteLine(currentKey + "---" + fileNameLength.ToString());
if (currentKey.Contains(requiredSunFolder))
{
if (currentKey.Contains(".zip")) //This helps to avoid errors related to (416) Requested Range Not Satisfiable
{
try
{
S3Download(bucketName, currentKey, downloadPath);
}
catch (Exception exTest)
{
string messageTest = currentKey + "-" + exTest;
}
}
}
}
}
}
Here is how it is called
static void Main(string[] args)
{
string downloadPath = #"C:\SourceFiles\TestDownload";
Task awsTask = MyAWS_S3_Helper.AsyncDownload("my-files", downloadPath, "mysubfolder");
awsTask.Wait();
}

Here is what I have done to download the files from S3 bucket,
var AwsImportFilePathParcel = "TEST/TEMP"
IAmazonS3 client = new AmazonS3Client(AwsAccessKey,AwsSecretKey);
S3DirectoryInfo info = new S3DirectoryInfo(client, S3BucketName, AwsImportFilePathParcel);
S3FileInfo[] s3Files = info.GetFiles(pattenForParcel);
now in s3Files, you have all the files which are on provided location, using for each you can save all files in to your system
foreach (var fileInfo in s3Files)
{
var localPath = Path.Combine("C:\TEST\", fileInfo.Name);
var file = fileInfo.CopyToLocal(localPath);
}

Related

How to download file from API using Post Method

I have an API using POST Method.From this API I can download the file via Postmen tool.But I would like to know how to download file from C# Code.I have tried below code but POST Method is not allowed to download the file.
Code:-
using (var client = new WebClient())
{
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
TransId Id = new TransId()
{
id = TblHeader.Rows[0]["id"].ToString()
};
List<string> ids = new List<string>();
ids.Add(TblHeader.Rows[0]["id"].ToString());
string DATA = JsonConvert.SerializeObject(ids, Newtonsoft.Json.Formatting.Indented);
string res = client.UploadString(url, "POST",DATA);
client.DownloadFile(url, ConfigurationManager.AppSettings["InvoicePath"].ToString() + CboGatePassNo.EditValue.ToString().Replace("/", "-") + ".pdf");
}
Postmen Tool:-
URL : https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed
Header :-
Content-Type : application/json
X-Cleartax-Auth-Token :b1f57327-96db-4829-97cf-2f3a59a3a548
Body :-
[
"GLD24449"
]
using (WebClient client = new WebClient())
{
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
client.Encoding = Encoding.UTF8;
//var data = "[\"GLD24449\"]";
var data = UTF8Encoding.UTF8.GetBytes(TblHeader.Rows[0]["id"].ToString());
byte[] r = client.UploadData(url, data);
using (var stream = System.IO.File.Create("FilePath"))
{
stream.Write(r,0,r.length);
}
}
Try this. Remember to change the filepath. Since the data you posted is not valid
json. So, I decide to post data this way.
I think it's straight forward, but instead of using WebClient, you can use HttpClient, it's better.
here is the answer HTTP client for downloading -> Download file with WebClient or HttpClient?
comparison between the HTTP client and web client-> Deciding between HttpClient and WebClient
Example Using WebClient
public static void Main(string[] args)
{
string path = #"download.pdf";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
client.Encoding = Encoding.UTF8;
var data = UTF8Encoding.UTF8.GetBytes("[\"GLD24449\"]");
byte[] r = client.UploadData(uri, data);
using (var stream = System.IO.File.Create(path))
{
stream.Write(r, 0, r.Length);
}
}
Here is the sample code, don't forget to change the path.
public class Program
{
public static async Task Main(string[] args)
{
string path = #"download.pdf";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
HttpClient client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, uri)
{
Content = new StringContent("[\"GLD24449\"]", Encoding.UTF8, "application/json")
};
request.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using (FileStream fs = File.Create(path))
{
await response.Content.CopyToAsync(fs);
}
}
else
{
}
}

AWS S3 transferutility UploadAsync succeeds but does not create file

I got to upload file & streams to S3 periodically and the file size usually under 50MB. What am seeing is TransferUtility.UploadAsync method returns success but the file was never created. This occurs sporadically. Below is the code we use. Any suggestions around this?
public TransferUtilityUploadRequest CreateRequest(string bucket, string path)
{
var request = new TransferUtilityUploadRequest
{
BucketName = bucket,
StorageClass = S3StorageClass.Standard,
Key = path,
AutoCloseStream = true,
CannedACL = S3CannedACL.AuthenticatedRead,
ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256
};
return request;
}
public async Task CreateS3ObjectFromStreamAsync(MemoryStream memeoryStream, string bucket, string filePath)
{
var ftu = new TransferUtility(client);
var request = CreateRequest(bucket, filePath);
request.InputStream = memeoryStream;
await ftu.UploadAsync(request);
}
public async Task CreateS3ObjectFromFileAsync(string sourceFilePath, string bucketName, string destpath)
{
var request = CreateRequest(bucketName, destpath);
request.FilePath = sourceFilePath;
var ftu = new TransferUtility(client);
await ftu.UploadAsync(request);
}
Please use Upload or UploadAsync.Wait. It worked for me!

How to create folders in google drive without duplicate using c#?

I am trying to create a folder on my google drive and check if it already exists. I am new to c#, so I wrote a code to create a specific folder in which I can upload my CSV files, but each time my application runs, it creates a duplicate folder with same name and I am now trying to figure out how to stop it.
class GoogleApi
{
private string[] Scopes = { DriveService.Scope.Drive };
private string ApplicationName;
private string FolderId;
private string FileName;
private string FilePath;
private string ContentType;
public GoogleApi(string fileName, string filePath)
{
ApplicationName = "MantisToDrive";
ContentType = "text/csv";
FileName = fileName;
FilePath = filePath;
}
public void Upload()
{
UserCredential credential = GetCredentials();
DriveService service = GetDriveService(credential);
FolderId = CreateFolderToDrive(service, "MantisData");
UploadFileToDrive(service, FileName, FilePath, ContentType);
}
private DriveService GetDriveService(UserCredential credential)
{
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
//verify User Credentials using client_secret.json file
private UserCredential GetCredentials()
{
UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath , true)).Result;
}
return credential;
}
private string UploadFileToDrive(DriveService service, string fileName, string filePath, string contentType)
{
var fileMatadata = new Google.Apis.Drive.v3.Data.File();
fileMatadata.Name = fileName;
fileMatadata.Parents = new List<string> { FolderId };
FilesResource.CreateMediaUpload request;
using (var stream = new FileStream(filePath, FileMode.Open))
{
request = service.Files.Create(fileMatadata, stream, contentType);
//service.Files.Delete(fileName).Execute();
request.Upload();
}
var file = request.ResponseBody;
return file.Id;
}
// creating folder in google drive to store CSV
public static string CreateFolderToDrive(DriveService service, string folderName)
{
bool exists = Exists(service,folderName);
if (exists)
return $"Sorry but the file {folderName} already exists!";
var file = new Google.Apis.Drive.v3.Data.File();
file.Name = folderName;
file.MimeType = "application/vnd.google-apps.folder";
var request = service.Files.Create(file);
request.Fields = "id";
var result = request.Execute();
return result.Id;
}
private static bool Exists(DriveService service, string name)
{
var listRequest = service.Files.List();
listRequest.PageSize = 100;
listRequest.Q = $"trashed = false and name contains '{name}' and 'root' in parents";
listRequest.Fields = "files(name)";
var files = listRequest.Execute().Files;
foreach (var file in files)
{
if (name == file.Name)
return true;
}
return false;
}
}
This should work (this checks whether the folder exists in your root folder. If not, the method will create a folder):
public static string CreateFolder(string folderName)
{
bool exists = Exists(folderName);
if (exists)
return $"Sorry but the file {folderName} already exists!";
var file = new Google.Apis.Drive.v3.Data.File();
file.Name = folderName;
file.MimeType = "application/vnd.google-apps.folder";
var request = service.Files.Create(file);
request.Fields = "id";
return request.Execute().Id;
}
private static bool Exists(string name)
{
var listRequest = service.Files.List();
listRequest.PageSize = 100;
listRequest.Q = $"trashed = false and name contains '{name}' and 'root' in parents";
listRequest.Fields = "files(name)";
var files = listRequest.Execute().Files;
foreach (var file in files)
{
if (name == file.Name)
return true;
}
return false;
}
In case somebody comes here from the future and the pastebin link is dead. This is how you can upload a file to your google drive:
public static async Task UploadFileAsync(string fileName)
{
var file = new Google.Apis.Drive.v3.Data.File();
file.Name = Path.GetFileName(fileName);
file.Parents = new List<string> {folderID};
byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray))
{
await service.Files.Create(file, stream, "some mime type").UploadAsync();
}
}

Access to sharepoint 2013 site from web api

I'm working on a communication between a MVC web app developed in c# and typescript and a remote sharepoint site. I want to execute crud operations for an excel file.
I'm able to read site properties in this way:
public async Task<string> getWebTitle(string webUrl, string usr, string psw)
{
//Creating Password
const string PWD = psw;
const string USER = usr;
const string RESTURL = "{0}/_api/web?$select=Title";
//Creating Credentials
var passWord = new SecureString();
foreach (var c in PWD) passWord.AppendChar(c);
var credential = new SharePointOnlineCredentials(USER, passWord);
//Creating Handler to allows the client to use credentials and cookie
using (var handler = new HttpClientHandler() { Credentials = credential })
{
//Getting authentication cookies
Uri uri = new Uri(webUrl);
handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
//Invoking REST API
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
string jsonData = await response.Content.ReadAsStringAsync();
return jsonData;
}
}
}
jsonData object returns site properties.
How I can do to read a file, for example test.txt, saved in Documents folder in "mysite"?
Do you mean that you want to get the content of file in SharePoint?
We can use CSOM to achieve it.
Here is a sample for your reference:
public static void getContentOfFileInDocLib(string siteUrl, string host, string sourceListName, string fileName)
{
siteUrl = siteUrl.EndsWith("/") ? siteUrl.Substring(0, siteUrl.Length - 1) : siteUrl;
ClientContext context = new ClientContext(siteUrl);
Web web = context.Site.RootWeb;
List source = web.Lists.GetByTitle(sourceListName);
context.Load(source);
context.Load(web);
context.ExecuteQuery();
FileCollection files = source.RootFolder.Files;
Microsoft.SharePoint.Client.File file = files.GetByUrl(siteUrl + "/" + sourceListName + "/" + fileName);
context.Load(file);
context.ExecuteQuery();
FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, file.ServerRelativeUrl);
string filePath = host + file.ServerRelativeUrl;
System.IO.Stream fileStream = fileInfo.Stream;
FileCreationInformation createFile = new FileCreationInformation();
byte[] bufferByte = new byte[1024 * 100];
System.IO.MemoryStream memory = new System.IO.MemoryStream();
int len = 0;
while ((len = fileStream.Read(bufferByte, 0, bufferByte.Length)) > 0)
{
memory.Write(bufferByte, 0, len);
}
//we get the content of file here
byte[] bytes = memory.GetBuffer();
//do something you want
//.......
}
Upload file to SharePoint Document Library.
public static void uploadFile(string siteUrl, string filePath, string fileName, string docLibName)
{
siteUrl = siteUrl.EndsWith("/") ? siteUrl.Substring(0, siteUrl.Length - 1) : siteUrl;
ClientContext context = new ClientContext(siteUrl);
List docLib = context.Web.Lists.GetByTitle(docLibName);
context.Load(docLib);
context.ExecuteQuery();
Byte[] bytes = System.IO.File.ReadAllBytes(filePath + fileName);
FileCreationInformation createFile = new FileCreationInformation();
createFile.Content = bytes;
createFile.Url = siteUrl + "/" + docLibName + "/" + fileName;
createFile.Overwrite = true;
Microsoft.SharePoint.Client.File newFile = docLib.RootFolder.Files.Add(createFile);
newFile.ListItemAllFields.Update();
context.ExecuteQuery();
}

Azure Storage Blob Rest Api Headers

I can't upload image to my azure storage by REST API.
This is my code:
using (var client = new HttpClient())
{
using (var fileStream = await _eventPhoto.OpenStreamForReadAsync())
{
var content = new StreamContent(fileStream);
content.Headers.Add("Content-Type", _eventPhoto.ContentType);
content.Headers.Add("x-ms-blob-type", "BlockBlob");
var uploadResponse = await client.PutAsync(new Uri("https://myservice.blob.core.windows.net/photos/newblob"),content);
int x = 2;
}
}
I get error about missing paramerer. Probably Authorization.
1) How to add missing headers?
2) Someone have working sample?
3) How to add Authorization?
Do you have a reason not to be using the client library that does this for you already? If you have a reason and you really want to use HttpClient, then you need to either a.) implement signing per spec, or b.) use a Shared Access Signature in your URI.
using System;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
namespace AzureSharedKey
{
class Program
{
private const string blobStorageAccount = "your_account";
private const string blobStorageAccessKey = "your_access_key";
private const string blobPath = "blob_path";
private const string blobContainer = "your_container";
static void Main(string[] args)
{
Console.WriteLine("Program Initiated..");
CreateContainer();
Console.ReadLine();
}
private async static void CreateContainer()
{
string requestMethod = "GET";
string msVersion = "2016-05-31";
string date = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
string clientRequestId = Guid.NewGuid().ToString();
string canHeaders = string.Format("x-ms-client-request-id:{0}\nx-ms-date:{1}\nx-ms-version:{2}", clientRequestId, date, msVersion);
string canResource = string.Format("/{0}/{1}/{2}", blobStorageAccount, blobContainer, blobPath);
string SignStr = string.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canHeaders, canResource);
string auth = CreateAuthString(SignStr);
string urlPath = string.Format("https://{0}.blob.core.windows.net/{1}/{2}", blobStorageAccount, blobContainer, blobPath);
Uri uri = new Uri(urlPath);
Console.WriteLine("urlPath "+ urlPath);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("x-ms-date", date);
client.DefaultRequestHeaders.Add("x-ms-version", "2016-05-31");
client.DefaultRequestHeaders.Add("x-ms-client-request-id", clientRequestId);
client.DefaultRequestHeaders.Add("Authorization", auth);
HttpResponseMessage response = client.GetAsync(uri).Result;
if (response.IsSuccessStatusCode)
{
string actualFilename= Path.GetFileName(blobPath);
string physicaPath = "D:/Others/AZ/";//change path to where you want to write the file
HttpContent content = response.Content;
string pathName = Path.GetFullPath(physicaPath + actualFilename);
FileStream fileStream = null;
try
{
fileStream = new FileStream(pathName, FileMode.Create, FileAccess.Write, FileShare.None);
await content.CopyToAsync(fileStream).ContinueWith(
(copyTask) =>
{
fileStream.Close();
});
Console.WriteLine("FileName: "+actualFilename);
Console.WriteLine("File Saved Successfully..");
}
catch
{
if (fileStream != null) fileStream.Close();
throw;
}
}
else
{
throw new FileNotFoundException();
}
}
private static string CreateAuthString(string SignStr)
{
string signature = string.Empty;
byte[] unicodeKey = Convert.FromBase64String(blobStorageAccessKey);
using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
{
byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(SignStr);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
string authorizationHeader = string.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
blobStorageAccount,
signature);
return authorizationHeader;
}
}
}
this code worked for me
Have a look at this example.
http://www.codeninjango.com/programming/azure/azure-blob-storage-rest-api/
It gives a step by step guide to using the Azure Blob Storage REST API to upload chunked files with SAS url's.

Categories