Click here to Skip to main content
15,904,652 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
When i try to upload bytes image to folder it give me error like:

Access to the path denied error in C#

What I have tried:

string fileName = "~/"+"Images" + "/Profile_Pic" + "/" + User_Id;
var directory = new DirectoryInfo(HttpContext.Current.Server.MapPath(fileName));
if (directory.Exists == false)
{
directory.Create();

}



byte[] imageBytes = Convert.FromBase64String(ImageByteArray);
System.IO.FileStream file = System.IO.File.Create(HttpContext.Current.Server.MapPath("~/Images/Profile_Pic/"+ User_Id));

file.Write(imageBytes, 0, imageBytes.Length);
file.Close();
Posted
Updated 11-Apr-17 3:04am
Comments
[no name] 11-Apr-17 8:55am    
Well, then you must not have permission to access that directory.
Member 12693375 12-Apr-17 0:40am    
i already granted to my folder then what next?

1 solution

You are trying to create a file with the same name as an existing directory. You probably forgot to append a file name or used the file name as directory name:
C#
string directoryName = "~/Images/Profile_Pic/" + User_Id;
// ...
System.IO.FileStream file = System.IO.File.Create(HttpContext.Current.Server.MapPath(directoryName + "/UserPic.ext"));
 
Share this answer
 
Comments
Member 12693375 12-Apr-17 0:39am    
Thanks for your answer.but not happy and request to you please do not copy paste the code from somewhere to here,if u do not know the answer.
Jochen Arndt 12-Apr-17 2:50am    
I have not copied code. I have typed it based on what you have posted to show an example how it must be done. Why should I not do?

It is an answer. It might not be the one you have expected but there is definitely a problem with your code:
You are checking if a directory exists, create it of not, and tries then to create a file with the same name. That won't work. There may be other errors too which are out of sight for readers of your question. But that does not make my solution not a answer.
Nguyen Trong 2024 23-Feb-24 3:22am    
This solution help me alot. Thanks man!
I keep thinking about setting permission for the directory but not the root caused. I forgot to set filename for it, it will directly Create file base on directory name --> Access Denied.
After verify directory exist, I used path.Combine between savePath and fileName --> Success
Here is my code
var savePath = @"C:\DataRawInfo";
if (!Directory.Exists(savePath))
{
    Directory.CreateDirectory(savePath);
}

var path = Path.Combine(savePath, defaultFileName);
File.WriteAllBytes(path, getFile);
Log.Information($"Store file:{defaultFileName} at {savePath} Success");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900