I am trying to upload the file that I have stored in MemoryStream using the following code.
private static void SaveStream(MemoryStream stream, string fileName)
{
var blobStorageService = new BlobStorageService();
UploadBlob(stream, fileName);
}
public void UploadBlob(MemoryStream fileStream,string fileName)
{
var blobContainer = _blobServiceClient.GetBlobContainerClient(Environment
.GetEnvironmentVariable("ContainerName"));
var blobClient = blobContainer.GetBlobClient(fileName);
blobClient.Upload(fileStream); <--- Error Message
}
Error Message: System.ArgumentException: 'content.Position must be less than content.Length.Please set content.Position to the start of the data to upload.'
This happened because the current position is at the end of the stream. You can set the position to the start of the stream before uploading
var blobClient = blobContainer.GetBlobClient(fileName);
fileStream.Position =0;
blobClient.Upload(fileStream)
Related
I'm uploading files to Azure Blob Storage with the .Net package specifying the encoding iso-8859-1. The stream seems ok in Memory but when I upload to the blob storage it ends with corrupted characters that seems that could not be converted to that encoding. It would seem as if the file gets storaged in a corrupted state and when I download it again and check it the characters get all messed up. Here is the code I'm using.
public static async Task<bool> UploadFileFromStream(this CloudStorageAccount account, string containerName, string destBlobPath, string fileName, Stream stream, Encoding encoding)
{
if (account is null) throw new ArgumentNullException(nameof(account));
if (string.IsNullOrEmpty(containerName)) throw new ArgumentException("message", nameof(containerName));
if (string.IsNullOrEmpty(destBlobPath)) throw new ArgumentException("message", nameof(destBlobPath));
if (stream is null) throw new ArgumentNullException(nameof(stream));
stream.Position = 0;
CloudBlockBlob blob = GetBlob(account, containerName, $"{destBlobPath}/{fileName}");
blob.Properties.ContentType = FileUtils.GetFileContentType(fileName);
using var reader = new StreamReader(stream, encoding);
var ct = await reader.ReadToEndAsync();
await blob.UploadTextAsync(ct, encoding ?? Encoding.UTF8, AccessCondition.GenerateEmptyCondition(), new BlobRequestOptions(), new OperationContext());
return true;
}
This is the file just before uploading it
<provinciaDatosInmueble>Sevilla</provinciaDatosInmueble>
<inePoblacionDatosInmueble>969</inePoblacionDatosInmueble>
<poblacionDatosInmueble>Valencina de la Concepción</poblacionDatosInmueble>
and this is the file after the upload
<provinciaDatosInmueble>Sevilla</provinciaDatosInmueble>
<inePoblacionDatosInmueble>969</inePoblacionDatosInmueble>
<poblacionDatosInmueble>Valencina de la Concepci�n</poblacionDatosInmueble>
The encoding I send is ISO-5589-1 in the parameter of the encoding. Anybody knows why Blob Storage seems to ignore the encoding I'm specifying? Thanks in advance!
We could able to achieve this using Azure.Storage.Blobs instead of WindowsAzure.Storage which is a legacy Storage SDK. Below is the code that worked for us.
class Program
{
static async Task Main(string[] args)
{
string sourceContainerName = "<Source_Container_Name>";
string destBlobPath = "<Destination_Path>";
string fileName = "<Source_File_name>";
MemoryStream stream = new MemoryStream();
BlobServiceClient blobServiceClient = new BlobServiceClient("<Your_Connection_String>");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(sourceContainerName);
BlobClient blobClientSource = containerClient.GetBlobClient(fileName);
BlobClient blobClientDestination = containerClient.GetBlobClient(destBlobPath);
// Reading From Blob
var line =" ";
if (await blobClientSource.ExistsAsync())
{
var response = await blobClientSource.DownloadAsync();
using (StreamReader streamReader = new StreamReader(response.Value.Content))
{
line = await streamReader.ReadToEndAsync();
}
}
// Writing To Blob
var content = Encoding.UTF8.GetBytes(line);
using (var ms = new MemoryStream(content))
blobClientDestination.Upload(ms);
}
}
RESULT:
can I append Images byte... ? I tried that but not works.. its increase the size but not reflect images.. its always return first image that I append first.. So Please help how can I append images ? json/text files are working fine but I m stuck on append image..
So,Please Help how can i do that..
Here is my code
CloudAppendBlob cloudAppendBlob = cloudBlobContainer.GetAppendBlobReference(fileName);
bool exist = await cloudAppendBlob.ExistsAsync();
if(!exist)
{
await cloudAppendBlob.CreateOrReplaceAsync();
}
cloudAppendBlob.Properties.ContentType = fileType;
stream.Position = 0;
await cloudAppendBlob.AppendBlockAsync(stream);
You can not append images with the same name. If you do that, it will replace the image file with the same name. If you upload another image then it would create a new image as per the uploaded one. Try the code below.
private CloudBlobContainer blobContainer;
public AzureBlobHelper()
{
try
{
// Get azure table storage connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
blobContainer = cloudBlobClient.GetContainerReference(CloudConfigurationManager.GetSetting("StorageContainer"));
// Create the container and set the permission
if (blobContainer.CreateIfNotExists())
{
blobContainer.SetPermissions(
new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
}
);
}
}
catch (Exception ExceptionObj)
{
// throw ExceptionObj;
}
}
public string UploadFile(string FileName, string LocalPath, string AzureBlobPath, string ContentType = "")
{
string AbsoluteUri;
try
{
CloudBlockBlob blockBlob;
// Create a block blob
blockBlob = blobContainer.GetBlockBlobReference(AzureBlobPath + FileName);
// Set the object's content type
blockBlob.Properties.ContentType = ContentType;
blockBlob.UploadFromFile(LocalPath);
// get file uri
AbsoluteUri = blockBlob.Uri.AbsoluteUri;
}
catch (Exception ExceptionObj)
{
throw ExceptionObj;
}
return AbsoluteUri;
}
I am using the following code to upload an XML file to an Azure Blob Storage account using the DotNetZip nuget package.
XmlDocument doc = new XmlDocument();
doc.Load(path);
string xmlContent = doc.InnerXml;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference(container);
cloudBlobContainer.CreateIfNotExists();
using (var fs = File.Create("test.zip"))
{
using (var s = new ZipOutputStream(fs))
{
s.PutNextEntry("entry1.xml");
byte[] buffer = Encoding.ASCII.GetBytes(xmlContent);
s.Write(buffer, 0, buffer.Length);
fs.Position = 0;
//Get the blob ref
var blob = cloudBlobContainer.GetBlockBlobReference("test.zip");
blob.Properties.ContentEncoding = "zip"
blob.Properties.ContentType = "text/plain";
blob.Metadata["filename"] = "test.zip";
blob.UploadFromStream(fs);
}
}
This code creates a zip file in my container. But when I download it and try to open it, I get the following error:
"Windows cannot open the folder. The compressed (zipped) folder is invalid". But the saved zipped file in my application directory can be unzipped fine and contains my xml file.
What am I doing wrong?
I am able to reproduce the problem you're having. Essentially the issue is that the content is not completely written in the zip file when you initiated the upload command. In my test, the zip file size on the local disk was 902 bytes however at the time of uploading the size of file stream was just 40 bytes and that's causing the problem.
What I did was split the two functionality where the first one just creates the file and other reads from file and uploads in storage. Here's the code I used:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference("test");
cloudBlobContainer.CreateIfNotExists();
using (var fs = File.Create("test.zip"))
{
using (var s = new ZipOutputStream(fs))
{
s.PutNextEntry("entry1.xml");
byte[] buffer = File.ReadAllBytes(#"Path\To\MyFile.txt");
s.Write(buffer, 0, buffer.Length);
//Get the blob ref
}
}
using (var fs = File.OpenRead("test.zip"))
{
var blob = cloudBlobContainer.GetBlockBlobReference("test.zip");
blob.Properties.ContentEncoding = "zip";
blob.Properties.ContentType = "text/plain";
blob.Metadata["filename"] = "test.zip";
fs.Position = 0;
blob.UploadFromStream(fs);
}
I am trying to upload files to Azure Data Box with C# and I am running into problems. Here is my code:
private void uploadBlob()
{
String storageconn = ConfigurationManager.AppSettings.Get("StorageConnectionString");
BlobServiceClient blobServiceClient = new BlobServiceClient(storageconn);
BlobContainerClient container = blobServiceClient.GetBlobContainerClient("democontainer");
Guid guid = Guid.NewGuid();
String filename = guid.ToString();
BlobClient blobClient = container.GetBlobClient(filename);
byte[] memoryArray = new byte[3252224];
var strm = new MemoryStream(memoryArray);
blobClient.Upload(strm);
strm.Close();
}
When the blobClient.Upload method executes, I get the following error:
The value for one of the httpheaders is not in the correct format
Does anyone have any ideas on what the problem is?
I have 2 methods to upload files to Blob Storage. 'UploadFileToContainer' is working fine, and i get files with data in container. The problem is 'UploadOrReplaceFileToContainer', where it's not possible to use file.Position = 0, returning the follow error:
System.NotSupportedException: 'Specified method is not supported.'
Can someone help?
public void UploadFileToContainer(Stream file, string fileName, string userId)
{
string uniqueFileName = GetFileNameUniqueId(fileName);
BlobClient blob = _container.GetBlobClient(fileName);
blob.Upload(file);
file.Position = 0;
BlobClient blob2 = _containerbackup.GetBlobClient(uniqueFileName);
blob2.Upload(file);
_log.LogFileUpload(fileName, uniqueFileName, userId, DateTime.Now);
}
public int UploadOrReplaceFileToContainer(Stream file, string fileName, string userId)
{
string uniqueFileName = GetFileNameUniqueId(fileName);
if (_container.GetBlobs().Any(b => b.Name == fileName))
{
_container.DeleteBlob(fileName);
}
BlobClient blob = _container.GetBlobClient(fileName);
blob.Upload(file);
file.Position = 0; //here is where i get the error
BlobClient blob2 = _containerbackup.GetBlobClient(uniqueFileName);
blob2.Upload(file);
int fileUploadId = _log.LogFileUpload(fileName, uniqueFileName, userId, DateTime.Now);
return fileUploadId;
}
You are getting this error suppose your stream type canseek type is false. You could create a new MemoryStream and copy the stream to the MemoryStream then seek it or just set the position.
System.IO.MemoryStream blobstream = new System.IO.MemoryStream();
inputblob.CopyTo(blobstream);
blobstream.Position = 0;
//blobstream.Seek(0, SeekOrigin.Begin);
blob.Upload(blobstream);
Also you could refer to other discussion about this:read a Stream and reset its position to zero.