"Unauthorized Access" when creating relative ~/Directory in ASP.NET - c#

from my aspx page i was tried to create a file. but it throws this error message if try to create the file from the root folder ( System.UnauthorizedAccessException: Access to the path '~/Image/User/mrrrrrfcom' is denied. )
Image1.ImageUrl = "~/Image/User/noneUserImage.jpg";
String folderPath = Path.Combine("~/Image/User/mrrrrrfcom", "mrrrrrfcom");
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
but its working if i give it path like this
String folderPath = Path.Combine("G:/AA/BB/CC/DD/Image/User/", "mrrrrrfcom");
but u need to create file from the root access so that the project will work for other computers to.

Ensure that the user account under which the website is running (eg "iis apppool\DefaultAppPool" -- or whatever app pool -- in IIS7) has appropriate permission.

Related

How to save text file in windows form application

I am creating a windows form application. for security reason i want to store licence information into a text file and want to encrypt it.
var serializer = new XmlSerializer(typeof(Licence));
var saveData = new Licence
{
ProductId = txtProductID.Text,
ProductKey = txtProductKey.Text,
CreatedDate = validate.CreationDate,
ExpireDate = validate.ExpireDate,
DaysLeft = validate.DaysLeft
};
using (var writeFile = File.OpenWrite("data.txt"))
{
serializer.Serialize(writeFile, saveData);
}
using this code i can able to create text file successfully. but when i publish this project and install it it gives me error.
error message is...
Access to the path "C:\Program Files (x86)\WebenixSystem\Metro Whole Sale\data.txt" is denied.
************** Exception Text **************
System.UnauthorizedAccessException: Access to the path 'C:\Program Files (x86)\WebenixSystem\Metro Whole Sale\data.txt' is denied.
How can i resolve this issue, and how can i encrypt this txt file? please help...
As the error suggests - you do not have permission to access the path you are trying to save the file to.
As the file will be encrypted, you do not have to hide it. Therefore, you could save it in the documents folder of the users account.
Using this line of code will return the path to the 'My Documents' folder. You can create a new folder within there or save the file directly to this path.
Note this is a relative path so it will work for all users.
String pathToDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Also to note: The license information won't be shared between different users. If user will logon with different account, the license data won't be found, because each user has its own "MyDocuments", "AppData" etc...

C# Filestream denied access

I'm trying to use C# to create a file, and read files back to fill out a rich text block. right now my problem is in creating/writing to the file.
FileStream fs = File.Create(#".\\tmp\" + fileName);
This is where I'm trying to write to. .\tmp\ exists, but when trying to write it it errors, saying
.\tmp\filename access is denied
The probably is that the user that is running the application probably doesn't have access to write to that directory. The easiest way to test that would be to run your application as administrator you should have access to write to that directory then.
You might also want to consider writing to the current directory no matter what user who is running your application should at the very least have access to that directory
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Probably you don't have access to the relative path.
To get your assembly directory:
private static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Then
FileStream fs = File.Create(Path.Combine(AssemblyDirectory, fileName));
You are using a relative path which leads to a location which you don't have access to.
A possible solution could be to:
Create a folder C:/data and make sure you have read and write rights to that folder
change the code to
string fileName = "file.txt";
FileStream fs = File.Create(#"C:/data/" + fileName);
This should create a file under C:/data with the filename "file.txt", assuming you have the correct read and write rights.
If you want a relative path to the current user's root directory, use:
string currentUserDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
This happened to me . I had had an anti-virus blocking access to any file when the writing or reading process happening from a C# program. I have just deactivated the anti-virus and the code worked like magic !

Creating directory and files in a remote server

I am trying to create directories and upload files to the server, but it won't give me access to. This is my code:
if (FileUploadControl.HasFile)
{
string path = "~/MSImages/";
string mappath = Server.MapPath(path);
if (FileUploadControl.PostedFile.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
{
string extension = FileUploadControl.PostedFile.FileName;
extension = extension.Substring(extension.LastIndexOf('.'));
if (!Directory.Exists(mappath))
Directory.CreateDirectory(mappath);
string filename = imgext + Request.QueryString["id"];
FileUploadControl.SaveAs(mappath + filename + extension);
}
}
It works when done on my local computer, but not when on my host. How to fix this?
This is most likely a permission issue. Your IIS account user doesn't have the appropriate permissions to change the resource on the other machine.
You could change the IIS user to a low-permission domain user that is just granted access to that specific machine's share. That should fix your issue.

How to access sql files exists under c# application directory

I have sql files that my c# application needs them to build tables and inserting some records.
I placed these sql files in a folder within the application (Under application directory).
How can i access these files from c# application, it looks like it doesn't exists !
this is the code to test if the file exist:
string _myFile = #"\SQL\fileName.sql";
if (File.Exists(_myFile))
{
MessageBox.Show("Exists");
}
else
{
MessageBox.Show("Not Exists");
}
the Folder under the application
App -- > SQL --> fileName.sql
Otherwise, if your using WinForms, you could use
string path = Path.Combine(Application.StartupPath, "mySqlFile.sql");
If your file is stored in a deeper folder, like ..\SQL\mySqlFile.sql just add this in the Path.Combine function as a parameter.
string path = Path.Combine(Application.StartupPath, "SQL", "mySqlFile.sql");
if you want to access
Bin-->Debug--> SQL files
string sExecutionPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // This will retrun the Debug Folder (i.e)., Exe Execution Path
Just change into real path of your file like:
string _myFile = #"C:\SQL\fileName.sql";
You can use the following code to access the files
string appLocation = System.IO.Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
string xslLocation = System.IO.Path.Combine(appLocation, #"SQL\fileName.sql");
if (System.IO.File.Exists(xslLocation))
MessageBox.Show("Exists");
else
MessageBox.Show("Not Exists");

Access to the path 'c:\windows\system32\inetsrv\config\' is denied

if (Fubrowse.HasFile)
{
string path = Path.GetFullPath(Fubrowse.PostedFile.FileName);
//string root = Path.GetPathRoot(path);
GetFilesFromDirectory(path.Substring(0, path.LastIndexOf("\\")));
}
else
GeneralClass.ShowMessageBox("Please Select File First.");
}
private void GetFilesFromDirectory(string DirPath)
{
try
{
DirectoryInfo Dir = new DirectoryInfo(DirPath);
FileInfo[] FileList = Dir.GetFiles("*.cs", SearchOption.AllDirectories);
foreach (FileInfo FI in FileList)
Here, path is c:\windows\system32\inetsrv\config\. I want to get all sub directories's file name in FileList array.
The Windows account that's running your code needs read access to the folder (that typically requires admin rights).
If you're running the program from Visual Studio, that's your account. Run VS as administrator and your code should work should work.
If it's a web app, the app pool account needs read access to the folder.
If it's a windows service, the host account needs access.
I had the same issue. I couldn't get files from the C:\Windows\system32\intesrv\config because my system was 64 bit and my request redirect to C:\Windows\SysWOW64\system32\intesrv\config
More explanation is given by this answer.
PS. My answer is left here just for those who will be in search in future

Categories

Resources