C# File Upload works locally; not on Azure - c#

I have a C# web application which uploads an image file to Azure Blob Storage. I am passing the local path of image file from a textbox (no File Upload Controller). This application works locally as expected. But when I publish it on Azure, it throws exception.
Could not find file (filename)
What changes should be made to run it on Azure?
Code :
CloudBlobContainer container = Program.BlobUtilities.GetBlobClient.GetContainerReference(Container);// container
container.CreateIfNotExists();
container.SetPermissions(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
CloudBlobDirectory directory = container.GetDirectoryReference(foldername);
// Get reference to blob (binary content)
CloudBlockBlob blockBlob_image = directory.GetBlockBlobReference(imageid);
using (var filestream = System.IO.File.OpenRead(image_path))
{
blockBlob_image.UploadFromStream(filestream);
}

Could not find file (filename)
The exception is caused by System.IO.File.OpenRead(filePath), as you Web Application is published to Azure. If you want use System.IO.File.OpenRead(filePath), you need to make sure that the filepath could be found in the WebApp.
What changes should be made to run it on Azure?
If you want to use the code on the Azure, you need to make sure that the file could be found in the Azue Website. You need to copy the file to Azure. If you want to upload file to the Azure blob, it is not recommanded. Since that you need to copy the file to Azure WebApp first.
Also As you mentioned that you could use FileUpload Controller to do that.

You're probably using the path to your computer which will be different on azure. You can try change the path to something like this:
string path = HostingEnvironment.ApplicationPhysicalPath + #"\YourProjectName\PathToFile"

Ok, Found the solution. Instead of passing file path to a textbox, I used FileUpload Controller. In the code-behind,
Stream image_path = FileUpload1.FileContent;
Actually, earlier too I had tried using FileUpload controller, but Server.MapPath(FileUpload1.Filename) and Path.GetFullPath(FileUpload1.FileName) were not giving the correct path.
Also,
using (var filestream = image_path)
{
blockBlob_image.UploadFromStream(image_path);
}
is replaced by
blockBlob_image.UploadFromStream(image_path);

Related

c# file upload to AWS

Hello and apologies in advance for the noob question. I'm also relatively new to c#. In ASP.NET core, I can save files via the file upload control to AWS S3. However, this relies on me saving the files first to a location on my hard drive and then I can send in the path for the AWS code to pick it up from there. I'm sure it will be a simple answer but I can't find this after a few days' searching. As anyone who uses my site can upload (and later download) pdfs and jpegs, how do I either (1) save the file to a temporary location on their machine or phone, or, preferably, (2) 'somehow' send in the path so the AWS code can pick it up? There are many posts stating how you can't get at the path for security reasons but as far as I can tell, the AWS code relies on it.
Here's the AWS code I'm using (from their documentation). It works for me (overwrites the last file and there's no error handling yet, but one thing at once for me). The bucketName and keyName are set up elsewhere.
It's how to send in the filePath without saving it anywhere that I can't get to work. The error just says that it can't find the file, understandably.
public void FileProcess(string filePath)
{
client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2);
Amazon.S3.Model.PutObjectRequest request = new Amazon.S3.Model.PutObjectRequest()
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath
};
PutObjectResponse response2 = client.PutObject(request);
}

Asp.Net C# Getting Full Path of a File

I am building a web application using WCF. I need to full path of a file to open and upload it to web service.
What I am doing is first opening a file by its full path, then take stream of it and finally upload it to service. My code is below
string Path = Server.MapPath( FileUpload1.PostedFile.FileName);
System.IO.Stream fileStream = File.OpenRead(#Path);
I can't get full path of the file for security reasons.
How can I read the file that users select?
Server.MapPath(FileUpload1.FileName) is the path to a file on the server. You cannot get the full path of the client machine of the file Using the FileUpload.
There is no need for the full client path to access it. You can use the FileBytes
property in order to read the contents of uploaded file.
As others have already suggested there's no reason you need the file path to the client in order to save a file on your server. In the case you need some clearer explanation for this, then please refer to these answers:
https://stackoverflow.com/a/3077008/2196675
https://stackoverflow.com/a/1130718/2196675

A default path when downloading PDF file in computer/mobile phone

I created a PDF webapp where users are able to generate various type of PDF on both the computer and mobile phone. However, i run my program on a localhost and this is how i save my PDF based on my computer's file directory
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
However, when i publish my webapp onto azure, i wasn't able to download from both my computer and mobile phone. Therefore i believe that it could be due to my default file directory.
Hence i would like to ask how to do a default file directory for all computer and mobile phone?
Or could it be i left out something that is necessary when the webapp is published online
Thanks.
PS : I hardcoded a default file path in order for me to test my application on a localhost to ensure a perfect working condition. Therefore i'm finding a way to find a default common file directory for all mobile/computer users when they attempt to download the PDF instead of my usual hard-coded file path
UPDATE
I tried using the method Server.MapPath but receive some error.
var doc1 = new Document();
var filename = Server.MapPath("~/pdf") + "MyTestPDF" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
// var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
//iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
using (var output = File.Create(filename))
{
iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
}
doc1.Open();
This is the error i received
ObjectDisposedException was unhandled by user code
Cannot access a closed file.
When you write a Web Application you shall never use hard coded paths, and the last place where you should save files is C:\Users !! It does not matter whether this is Azure or not. It is general rule for any kind of web applications!
In your case I suggest that you create a folder within your application named pdf or something like that and save files there with the following code:
var fileName = Server.MapPath("~/pdf") + filename;
using (var output = File.Create(fileName) )
{
// do what you want with that stream
// usually generate the file and send to the end user
}
However there is even more efficient way. Use the Response.OutputStream and write the resulted PDF directly to the response. Will save you a lot of space on the local server, and the logic to delete unused generated files.

How to Delete from from folder in wcf

i have a web app to upload files to one folder. Now I want to delete the file from that folder using a WCF service. In asp.net we use string filePath = Server.MapPath(FPath); but this is not working in WCF.
Any help?
I'm guessing you just need to change it to:
string filePath = HttpContext.Current.Server.MapPath(FPath)

Download File via Tamir.SharpSSH.Sftp.Get()

I'm trying to download a file using the Tamir SSH library. I'm able to connect to the remote FTP site, upload files to the site, but I'm getting exceptions when trying to download. I've given IIS_IUSRS full control of the local directory as well as ASPNET. I've tested an I'm able to create a text file in the same local directory I'm trying to download to. Any ideas?
string SFTP_HOST = ConfigurationManager.AppSettings["AccentivFtpHost"];
string SFTP_USERNAME = ConfigurationManager.AppSettings["AccentivFtpUsername"];
string SFTP_PASSWORD = ConfigurationManager.AppSettings["AccentivFtpPassword"];
Sftp client = new Sftp(SFTP_HOST, SFTP_USERNAME, SFTP_PASSWORD);
client.Connect(22);
client.Get("test.txt", "c:\\test.txt");
You probably lack a '/' character in the file directory. You may need to put it either in the Get function call before the "test.txt" like "/test.txt" or at the end of your AccentivFtpHost value in the app config file.

Categories