C#, Creating .txt file - c#

I am having trouble creating a .txt file with the code below. I get an exception as follows:
Unhandled exception: System.unauthorizedAccessException: Access to the
path 'C:\log.txt' is denied.
I have looked online and done similar things to what is on the api. Below is my code, so you can understand what my train of logic is. What do you think causes this exception? Thanks in advance!
static StreamWriter swt;
static string logFile = #"C:\log.txt";
static FileStream fs;
static void Main(string[] args)
{
Console.Out.WriteLine(swt);
string root = args[0];
if (!File.Exists(logFile))
{
try
{
fs = File.Create(logFile);
}
catch (Exception ex)
{
swt.WriteLine("EXCEPTION HAS BEEN THROWN:\n " + ex + "\n");
}
{
}
}
}

You're most likely getting this error because a standard user cannot write to the root of a drive without elevated permissions. See here.

Detect the folder permissions. It has to has write permission on the logged user.

Yes, it is permission error. You don't have enough rights to write file in C: drive. To write in these types of folder/drive you need admin permission.
You can give your application admin rights. Simple way is enforce your application to start in admin account/rights only. To achieve this
Solution Explorer -> your project -> Add new item (right click) -> Application Manifest File.
In this file change requestedExecutionLevel to
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
These enforce your application with admin rights only. On Windows 8/7/Vista it will display UAC (User Access Control) dialog box when you start the application.
Hope this will help you....

Related

Access is denied in windows forms

Iam asking this question as a series to the below link
Unable to delete .exe file through c#
While i was debugging the application,iam able to delete the .exe file.But when i try to delete the application after installing in the desktop,again iam getting the exception message as "Access is denied".
Edit:-
The code i am using to delete the file
public bool deleteAppExecutable(string filePath)
{
try
{
if (File.Exists(filePath))
{
var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
di.Attributes &= ~FileAttributes.ReadOnly;
SetAccessRule(filePath);
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
File.Delete(filePath);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public static void SetAccessRule(string filePath)
{
FileInfo dInfo = new FileInfo(filePath);
FileSecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Delete, AccessControlType.Allow));
dInfo.Refresh();
dInfo.SetAccessControl(dSecurity);
}
I found the solution why i am getting the "access is denied" exception in my application.
Since i am deleting a file inside the application through code i need to have the privilege of "Administrator".
One way is to make the user login manually as administrator.But that is not a better option.
Another way is to create an App Manifest file within your project and set the level as "administrator."
Creating App Manifest--> Right click on the project->Add new item-->Select App Manifest option from the right pane->Click ok
Open the manifest file and change the level to "requireAdministartor".
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will solve the issue while running the application,it will prompt user to run as administrator.
Hope this will be helpful to someone in future. :)
Check that you have full permissions on the folder the exe is contained in (and all of it's child objects)

Directory.CreateDirectory access to path is denied?

I have server-client application, it's a file manager
my problem is when I go inside a folder which requires access control like system folders, it becomes to read-only, but I need to move/delete or create new folder, how can I get the permission to do that?
here's how I create a new folder at the server side
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
Directory.CreateDirectory(path + current);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
There are often directories on a drive that even a user with administrator privileges cannot access. A directory with a name like "HDDRecovery" is quite likely to be troublesome like this. Surely it contains sensitive data that helps the user recover from disk failure. Another directory that fits this category is "c:\system volume information", it contains restore point data.
An admin can change the permissions on folders like this. But of course that doesn't solve the real problem nor is it a wise thing to do. Your user can't and shouldn't. Be sure to write code that deals with permission problems like this, simply catch the IOExeption. Keep the user out of trouble by never showing a directory that has the Hidden or System attribute set. They are the "don't mess with me" attributes.
If you want to remove directory read-only attribute use this: http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/cb75ea00-f9c1-41e5-ac8e-296c302827a4
If you want to access system folders you can run your program as local administrator.
I had a similar problem (asp.net MVC vs2017) with this code:
Directory.CreateDirectory("~/temp");
Here is my solution:
// Create path on your web server
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/temp"));
I also ran into an issue similar to this, but I was able to manually navigate through Windows Explorer and create directories.
However, my web app, running in VS on my laptop, hosted through my local IIS and not the built-in IIS deal for VS, was triggering the Access Denied issue.
So when I was hitting the error in code, I drilled down to glean more data from the System.Environment object and found the user, which of course was the App Pool that my app was running under in IIS.
So I opened IIS and opened the Advanced Settings for the app pool in question and changed the Identity to run under Network Service. Click OK. "cmd -> iisreset" for good measure. Try the app again, and SUCCESS!!!!
I had the same issue when creating a directory. I used DirectorySecurity as shown below:
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Also keep in mind about the security as explained by Hans Passant's answer.
Full details can be found on MSDN.
So the complete code:
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
//Directory.CreateDirectory(path + current);
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
My suspicion is that when you are running the application in client/server mode, the server portion needs to be running as Administrator, in addition to possibly removing read-only or system flags, to be able to do what you want.
That said, I agree with #HansPassant- it sounds like what you are trying to do is ill-advised.
Solved:
Directory created on remote server using below code & setting.
Share folder and give the full permission rights also in Advance
setting in the folder.
DirectoryInfo di = Directory.CreateDirectory(#"\\191.168.01.01\Test\Test1");
Test is destination folder where to create new Test1 folder(directory)

Remove Read-Only Attribute On FOLDER On A Network Share

I am having an issue that is really killing me.
I have a directory that when I go to the properties window, shows Read-Only as partially checked (not a full check box, but the box is filled).
So I looked in the directory and I checked all the files, none of them have the read-only attribute. Only the folder has it, and only partially.
I tried the following code:
if (directoryInfo.Exists)
{
try
{
directoryInfo.Attributes &= ~FileAttributes.ReadOnly;
foreach (FileInfo f in directoryInfo.GetFiles())
{
f.IsReadOnly = false;
}
}
catch (Exception e)
{
throw e;
}
}
It still did not work. I can right click on the folder and manually remove the read-only permissions but I need to be able to do this in code. The code executes but does not error.
Anyone have any idea what the issue could be? My only guess is because the folder is on a network share (in the form of \\computer\folder\subfolder), that I might need special rights in order to change permissions on a folder?
Please someone help.
Thanks in advance
readonly on folders is used by Windows internally... if you really need to change it then is some work involved (Registry and changing alot of folders)... see http://support.microsoft.com/kb/256614/en-us
Why do you need to make that change ?
EDIT - some information on Powershell and TFS:
http://codesmartnothard.com/ExecutingPowerShellScriptsOnRemoteMachinesWithTFS2010AndTeamDeploy2010.aspx
http://blogs.msdn.com/b/yao/archive/2011/06/15/tfs-integration-pack-and-scripting-using-powershell.aspx
or try a normal "batch file" (.bat) with "attrib -r" on the folder

Getfiles() UnAuthorizedAccessAcception in WIN7

Problems
UnAuthorizedAccessException: When searching a directory recursively such as C:\
A "Access to the path 'c:\Documents and Settings\' is denied." Occurs even with UAC Priveledges upgraded & Administrator group access.
Attempted Methods
Try & Catch: Using either one of these methods(Exception, UnAuthorizedAccessException, Blank Catch, continue)
Questions
How do you handle this kind of exception and continue running your program as normal? This needs to work both on non-admin and administrator accounts.
Example Code
using System;
using System.IO;
namespace filecheck
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int html = 0;
try
{
string[] filePaths = Directory.GetFiles(#"c:\", "*.html", SearchOption.AllDirectories);
foreach (string files in filePaths)
{
if (Convert.ToBoolean(files.IndexOf("html")))
{
html++;
}
Console.WriteLine(files);
i++;
}
Console.Write("# Files found: {0} Html: {1)", i, html);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
}
Unfortunately the only way to handle this is by doing the recursion manually. Even in Microsoft's own sample code they do it this way, just to avoid that the whole search fails because one or more directories can not be accessed.
So in other words, only use SearchOption.AllDirectories when you're searching a limited subset of directories which you're certain won't contain any directories which you won't have access to.
To get your program working with both admin and non-admin users you either need to impersonate the user or re-build your application to "Run as Administrator" every time it is being executed or used by any user. To build this kind of application you need to add app.manifest file to your project and un-comment the following line of setting in app.manifest
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
For more read here: http://midnightprogrammer.net/post/How-To-Build-UAC-Compatible-Application-In-NET.aspx

How to Delete a file using asp.net?

i write the code in asp.net using c# to delete the file in my computer, but it is not deleting please help me thank u. this is my code, i write in button click event
string path = "E:\\sasi\\delt.doc";
FileInfo myfileinf = new FileInfo(path);
myfileinf.Delete();
public void DeleteFileFromFolder(string StrFilename)
{
string strPhysicalFolder = Server.MapPath("..\\");
string strFileFullPath = strPhysicalFolder + StrFilename;
if (IO.File.Exists(strFileFullPath)) {
IO.File.Delete(strFileFullPath);
}
}
In order to delete a file you must ensure that the account has sufficient permissions. In general ASP.NET applications run under limited permission account such as Network Service. For example if your application runs under IIS 6 you could go to the Administration Console and set a custom account in the application pool properties:
alt text http://i.msdn.microsoft.com/Bb969101.SharePoint_SQL_TshootingFig3%28en-US,SQL.90%29.jpg
You need to ensure that the account is member of the IIS_WPG group.
Make sure the ASP user has permissions to this folder. By default this user is not given access to much of the harddrive..

Categories