Given Paths Format is Not Supported (Visual Studio / Azure)? - c#

When i click the download link it send me to a error page trying to debug it its telling me that my given paths format is not supported
In my controller class:
public async Task<ActionResult> DownloadBlob(string file, string extension)
{
string downloadPath = await repo.DownloadBlobAsync(file, extension);
return Json(downloadPath);
}
In My Blob Storage class:
public async Task<string> DownloadBlobAsync (string file, string fileExtension)
{
_cloudBlobContainerx = _cloudBlobClientx.GetContainerReference(containerNamex);
CloudBlockBlob blockBlob = _cloudBlobContainerx.GetBlockBlobReference(file + "." + fileExtension);
var path = downloadPath + file + "." + fileExtension;
using (var fileStream = System.IO.File.OpenWrite(path))
{
fileStream.Position = 1;
//fileStream.Seek(0, SeekOrigin.Begin);
await blockBlob.DownloadToStreamAsync(fileStream);
return path;
}
}
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NotSupportedException: The given path's format is not supported
The source of the error :
using (var fileStream = System.IO.File.OpenWrite(path))

According to your description, I suggest you could set a break point to check the value of downloadPath or 'path' field.
I have created a simple demo to download a blob file to a local folder path. It works fine. You could refer to.
string containerNamex = "container002";
string file = "MyTest"; //a blob file named MyTest.txt
string fileExtension = "txt";
string downloadPath = #"D:\MyBlob\";
CloudBlobClient _cloudBlobClientx = storageAccount.CreateCloudBlobClient();
_cloudBlobContainerx = _cloudBlobClientx.GetContainerReference(containerNamex);
CloudBlockBlob blockBlob = _cloudBlobContainerx.GetBlockBlobReference(file + "." + fileExtension);
var path = downloadPath + file + "." + fileExtension;
using (var fileStream = System.IO.File.OpenWrite(path))
{
fileStream.Position = 1;
blockBlob.DownloadToStreamAsync(fileStream);
Console.WriteLine("success");
}
The result like this:

Related

How to way extract format .gz/.zip/.rar/.tar.gz in .net core mvc c#

I have issue when action open file follow format .gz/.tar.gz
This is image error
This is code:
public void Check(string path)
{
foreach (var fileName in Directory.GetFiles(path))
{
if (Path.GetExtension(fileName) == ".gz" && Path.GetFileNameWithoutExtension(fileName).Contains("tar"))
{
Console.WriteLine(fileName);
ExtractTGZ(fileName, Path.GetDirectoryName(fileName) + #"\" + Path.GetFileNameWithoutExtension(fileName));
System.IO.File.Delete(fileName);
}
}
}
The System.IO.Compression namespace contains the following types for compressing and decompressing files and streams. You can also use these types to read and modify the contents of a compressed file.
string fileName = Guid.NewGuid() + ifile.FileName;
string path = Path.Combine(FilesTempPath, fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
ifile.CopyTo(fileStream);
}
var FileZipPath = FilesTempPath + "\\" + fileName;
ZipFile.ExtractToDirectory(FileZipPath, FilesTempPath);
The following example from MSDN shows how to use the GZipStream class to compress and decompress a directory of files.

Exception when trying to download file from google storage : "The specified data could not be decrypted"

I created Bucket on google Storage and I programmatically uploaded some files on it. When I try to download them, I get this exception:
The specified data could not be decrypted
I wrote code such that
GoogleCredential credential = null;
var jsonFileBytes = Properties.Resources.stitcherautoupdate_55bd51f48cf0;
var jsonFileString = Encoding.UTF8.GetString(jsonFileBytes, 0, jsonFileBytes.Length);
var json = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Object>(jsonFileString);
var jsonString = json.ToString();
credential = GoogleCredential.FromJson(jsonString);
StorageClient = StorageClient.Create(credential);
StorageClient.DownloadObject(bucketName, fileName, fileStream);
My recommendation regarding your issue is to try following the methods for upload and download mentioned in the documentation. Once you get it working, you can start slowly changing the code so you know which part is the one causing the issue.
This document describes how you should first configure your Cloud Storage client library and setting up authentication.
A sample code for uploading an object:
private void UploadFile(string bucketName, string localPath,
string objectName = null)
{
var storage = StorageClient.Create();
using (var f = File.OpenRead(localPath))
{
objectName = objectName ?? Path.GetFileName(localPath);
storage.UploadObject(bucketName, objectName, null, f);
Console.WriteLine($"Uploaded {objectName}.");
}
}
For downloading an object:
private void DownloadObject(string bucketName, string objectName,
string localPath = null)
{
var storage = StorageClient.Create();
localPath = localPath ?? Path.GetFileName(objectName);
using (var outputFile = File.OpenWrite(localPath))
{
storage.DownloadObject(bucketName, objectName, outputFile);
}
Console.WriteLine($"downloaded {objectName} to {localPath}.");
}

can't access Image after uploade in asp core 2.1

I can't access photos to view after uploade.
This is the uploade code
`
public async Task<string> Upload_Image(FormFile file,string name)
{
var newFileName = string.Empty;
if (file.Length > 0)
{
var fileName = string.Empty;
string PathDB = string.Empty;
//Getting FileName
fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
//Assigning Unique Filename (Guid)
var myUniqueFileName = Convert.ToString(Guid.NewGuid());
//Getting file Extension
var FileExtension = Path.GetExtension(fileName);
// concating FileName + FileExtension
newFileName = myUniqueFileName + FileExtension;
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
_env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), name);
}
// Combines two strings into a path.
fileName = _env.WebRootPath + '\\' + newFileName;
// if you want to store path of folder in database
PathDB = name+"/" + newFileName;
newFileName = PathDB;
using (FileStream fs = System.IO.File.Create(fileName))
{
await file.CopyToAsync(fs);
fs.Flush();
}
}
return newFileName;
}`
I am using ID as argument for parameter 'name'.
When I am trying to access the photo using "/ID/whatEverhere.jpg"
return NOTFOUND ??????
You are storing your file in :
fileName = _env.WebRootPath + '\\' + newFileName;`
...
using (FileStream fs = System.IO.File.Create(fileName))
And you return :
PathDB = name+"/" + newFileName;
newFileName = PathDB;
...
return newFileName;
So, that isn't the same path, there isn't your ID in the path you store the file !
I sujest you should cleanup your code.

download azure container as zip file asp.net mvc

i want to download all files in container on azure as zip file and make the path to download be dynamic
this the right now code
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string[] arr = userName.Split('\\');
string path = $#"C:\Users\{arr[1]}\Downloads\";
CloudBlobContainer contianner = BlobClient.GetContainerReference(contianerName);
var list = contianner.ListBlobs();
/// Console.WriteLine(list.Count());
string[] FilesName = new string[list.Count()];
int i = 0;
foreach (var blob in list)
{
string[] Name = blob.Uri.AbsolutePath.Split('/');
FilesName[i++] = Name[2];
// Console.WriteLine(Name[2]);
CloudBlockBlob blockBlob = contianner.GetBlockBlobReference(Name[2]);
System.IO.Directory.CreateDirectory($#"{path}ImagesPath");
using (var fileStream = System.IO.File.OpenWrite($#"{path}\ImagesPath\{Name[2]}"))
{
blockBlob.DownloadToStream(fileStream);
}
}
You need to finish your job using 3 steps.
Step 1, Download all the files to a folder. I suggest you create a folder under your content folder of your web application.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("storage connection string");
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
string containerName = "mycontainer";
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
var blobs = container.ListBlobs(string.Empty, true);
string currentDateTime = DateTime.Now.ToString("yyyyMMddhhmmss");
string directoryPath = Server.MapPath("~/Content/" + containerName + currentDateTime);
System.IO.Directory.CreateDirectory(directoryPath);
foreach (CloudBlockBlob blockBlob in blobs)
{
string[] segements = blockBlob.Name.Split('/');
string subFolderPath = directoryPath;
for (int i = 0; i < segements.Length - 1; i++)
{
subFolderPath = subFolderPath + "\\" + segements[i];
if (!System.IO.Directory.Exists(subFolderPath))
{
System.IO.Directory.CreateDirectory(subFolderPath);
}
}
string filePath = directoryPath + "\\" + blockBlob.Name;
blockBlob.DownloadToFile(filePath, System.IO.FileMode.CreateNew);
}
Console.WriteLine("Download files successful.");
Step 2, After download the files, we could compress the folder using System.IO.Compression.ZipFile class. To use it, we need to add references to 2 assemblies. System.IO.Compression and System.IO.Compression.FileSystem.
System.IO.Compression.ZipFile.CreateFromDirectory(directoryPath, directoryPath + ".zip");
Console.WriteLine("Compress the folder successfully");
Step 3, Since the zip file is generated in the content folder, you could generate the URL for downloading operation.
string url = "http://hostname:port/content/" + containerName + currentDateTime + ".zip";

How to set the filename when uploading in asp.net

I am using the following code to upload a file and save it on the disk. The filename is like:
BodyPart4353453453
E.g. When I upload a file called alfa.txt it will be saved as BodyPart24245343.
How can I set the filename each time?
var uploadFolder = "/Content/Images/" + listingId;
var provider = GetMultipartProvider(uploadFolder);
var result = await Request.Content.ReadAsMultipartAsync(provider);
Try somthing like this.
// change file name with its extension
var fileName = Guid.NewGuid().ToString() +
System.IO.Path.GetExtension(file.FileName);
var uploadUrl = Server.MapPath("~/uploads");
file.SaveAs(Path.Combine(uploadUrl, fileName));

Categories

Resources