UnauthorizedAccessException when saving file, but can create a directory - c#

I'm trying to save a file to the disk but I get UnauthorizedAccessException.
The error says I have to get the right permissions on the folder, and I've tried every possible user I can find but it doesn't work.
Tried the following users
Network
Network Services
IUSR
IUSR_[Computername]
And given the full rights without it working.
What I find really strange is that I create a directory before I try to save the file and that works perfectly, it's when trying to save a file to that new directory that I get the UnautorhizedAccessException.
The code is the following:
[HttpPost]
public ActionResult Images(HttpPostedFileBase file, string boatId)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images/" + boatId));
Directory.CreateDirectory(path);
file.SaveAs(path);
}
return View($"Filen på {boatId} har laddats upp");
}
Any ideas at what I'm missing?

Turns out what I was trying to do was saving the folder and not the file, I forgot to combine the fileName with the path.
Changed the Save part to the following:
file.SaveAs(Path.Combine(path, fileName));
Which solved the whole thing for me.

Related

Download file from base64 in xamarin forms

I'm trying to download a file (that can be either image or PDF) that I've saved in my DB. I get the file in a string format, so I want to download this file. The problem is, I don't get any error, it just doesn't show the downloaded file on its folder.
Here is what I have so far.
string caminho = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string caminho_arquivo = Path.Combine(caminho, nome_arquivo);
var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(arquivo.arquivo));
File.WriteAllText(caminho_arquivo, decoded);
The code below:
string caminho = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
would show the path like:
"/data/user/0/packagename/files/filename"
In Internal Storage, you couldn't see the files without root permission.
But you could use the code to check the file exist or not in the internal storage.
if (File.Exists(caminho_arquivo))
{
}
If you want to view it, you could use adb tool. Please refer to the way in the link about the adb tool.
How to write the username in a local txt file when login success and check on file for next login?

How to find a file without specific path

Im trying to send a compressed file with an email.
So the step is :
1. Compressed the file that we want to.
2. Send the email in outlook, with the attachment from the compressed file.
My problem is when the application try to search for the compressed file, it wont find because my path didnt right.
Here's the code
using (ZipFile zip = new ZipFile())
{
//zip.UseUnicodeAsNecessary = true;
zip.AddDirectory(#"Y:\"+tglskrg+"\\Result");
zip.Save(#"C:\Users\Desktop\"+tglskrg+".zip");
}
string path = Path.Combine(Directory.GetCurrentDirectory(), tglskrg + ".zip");
//Send email code(which basicly work);
my problem is , the file is saved in desktop
the actual result is , when the apps try to search for the file, the apps look in the path directory which from the code i write, the path is in the Debug folder from the application.
Anyone can help ? or maybe where did i do wrong?
Thankyou
Maybe I am not understanding your question; but, if you want to refer to the desktop folder, use Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory).
For example, you are trying to save your zip file to the desktop,
change this:
zip.Save(#"C:\Users\Desktop\"+tglskrg+".zip");
to this:
zip.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), tglskrg + ".zip"));

Xamarin media plugin get android image path

I am using the media plugin for xamarin forms (by james montemagno) and the actual taking of the picture and storing it works fine, I have debugged the creation of the image on the emulator and it is stored in
/storage/emulated/0/Android/data/{APPNAME}.Android/files/Pictures/{DIRECTORYNAME}/{IMAGENAME}
however in my app it will get a list of file names from an API I want to check if the image exists in that folder.
The following works fine on IOS
var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, App.IMAGE_FOLDER_NAME);
jpgFilename = System.IO.Path.Combine(jpgFilename, name);
I have tried the 2 following methods for getting it on android but both are incorrect
var documentsDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, App.IMAGE_FOLDER_NAME);
jpgFilename = System.IO.Path.Combine(jpgFilename, name);
Java.IO.File dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DataDirectory + "/" + App.IMAGE_FOLDER_NAME + "/" + name);
dir ends up as
/storage/emulated/0/data/{DIRECTORY}/{IMAGENAME}
jpgFileName ends up as /data/data/{APPNAME}.Android/files/{DIRECTORYNAME}/{IMAGENAME}
I dont want to hardcode anything in the paths but neither of these are right. I could not find anything in the GIT documentation for getting the file path except by looking at the path of the file created when taking a picture
The problem
I had the same kind of issue with Xamarin Media Plugin. For me, the problem is:
we don't really know where the plugin save the picture on android.
After reading all documentation I found, I just noted this:
... When your user takes a photo it will still store temporary data, but also if needed make a copy to the public gallery (based on platform). In the MediaFile you will now see a AlbumPath that you can query as well.
(from: Github plugin page)
so you can save your photo to your phone gallery (it will be public) but the path is known.
and we don't know what means "store the temporary data".
Solution
After investigating on how/where an app can store data, I found where the plugin stores photos on Android >> so I can generate back the full file names
In your Android app, the base path you are looking for is:
var basePath = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath
It references your app's external private folder. It looks like that:
/storage/emulated/0/Android/data/com.mycompany.myapp/files
So finally to get your full file's path:
var fullPath = basePath + {DIRECTORYNAME} + {FILENAME};
I suggest you to make a dependency service, for instance 'ILocalFileService', that will expose this 'base path' property.
Please let me know if it works for you !
I resolved a similar problem. I wanted to collect all files for my app in a folder visible to all users.
var documentsDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(
Android.OS.Environment.DirectoryDocuments);
If you want to create Directory, add to your class using System.IO; and you have the same functions in a normal .NET application.
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
If you want to create files or directory, you can use PCLStorage.
public async Task<bool> CreateFileAsync(string name, string context)
{
// get hold of the file system
IFolder folder = FileSystem.Current.LocalStorage;
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync(name,
CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync(context);
return true;
}
to get the private path
var privatePath = file.Path;
to get the public Album path
var publicAlbumPath = file.AlbumPath;
se the documentation here https://github.com/jamesmontemagno/MediaPlugin

I'm unable to reference an uploaded file

Sorry if this is a simple question but I'm still not to competent at coding. Via ASP.net c# I upload a file to Uploads with an UploadHandler.ashx which is working fine. Then I try to reference the file. Before referencing it I check to see if the file exists with
if (File.Exists(filePath))
{
Do stuff;
}
else
{
Do other stuff;
}
When debugging the filePath is showing as "../Uploads/P3301_5_40_4.bin" which is what I am expecting but the if file exists is returning false. Am I entering the file path with an incorrect syntax or is there something else I am messing up? I confirmed the file is there.
File.Exists is probably looking for the physical path to the file on the server. Try using Server.MapPath which maps the virtual path in your website to the physical path on the server.
string physicalPath = Server.MapPath(filePath);
if (System.IO.File.Exists(physicalPath))
{
// do stuff
}
else
{
// handle error
}
You should convert filePath using something like this:
filePath = HttpContext.Current.Server.MapPath(filePath);

Saving an uploaded file with HttpPostedFileBase.SaveAs in a physical path

I'd like to save an uploaded file to a physical path by the method HttpPostedFileBase.SaveAs().
When I choose a physical path, an exception appears indicates that the path must be virtual.
var fileName = Path.GetFileName(fileurl.FileName);
var path = "C:/Projets" + fileName;
fileurl.SaveAs(Server.MapPath(path));
How can I change my code to be able to save the file every where I want?
The Server.MapPath works only with physical locations that are part of the website. If you want to save the file outside you could use the following:
var fileName = Path.GetFileName(fileurl.FileName);
fileurl.SaveAs(Path.Combine(#"c:\projects", fileName));
Make sure though that the account under which your application pool is executing is granted write permissions to this folder.
Server.MapPath is for virtual path. You can try to use Path.GetFullPath(path).

Categories