How to Delete a file using asp.net? - c#

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..

Related

How can i save files in folder within the IIS of outside of the Application folder in asp.net

In my web application, i have some files those are saving within application it's creating a folder for saving files but i need to save those file outside of the application and inside of IIS.how can i do this?
With in application Folder we are using below code
Server.MapPath(Path)
For Saving in IIS How can i Write?
Thank you
you need to create a virtual directory that points ti the folder outside.
Go to IIS right click on your website. click on Add Virtual directry from the menu.Give an alias for the directory select your desired folder and you are done. it will consider this outside folder as an internal folder and work the same way. check this link How to: Create and Configure Virtual Directories in IIS 7.0
Disclaimer: but you will have to do this after hosting to iis i.e publishing. while using visual studio in dev environment i.e debugging it will store in internal directories only
Edit: for creating virtual directories this is the code. I have not tested its validity.
static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
{
// metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
// for example "IIS://localhost/W3SVC/1/Root"
// vDirName is of the form "<name>", for example, "MyNewVDir"
// physicalPath is of the form "<drive>:\<path>", for example,"C:\Inetpub\Wwwroot"
try
{
DirectoryEntry site = new DirectoryEntry(metabasePath);
string className = site.SchemaClassName.ToString();
if ((className.EndsWith("Server")) || (className.EndsWith("VirtualDir")))
{
DirectoryEntries vdirs = site.Children;
DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace("Service", "VirtualDir")));
newVDir.Properties["Path"][0] = physicalPath;
newVDir.Properties["AccessScript"][0] = true;
// These properties are necessary for an application to be created.
newVDir.Properties["AppFriendlyName"][0] = vDirName;
newVDir.Properties["AppIsolated"][0] = "1";
newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", ("IIS://".Length)));
newVDir.CommitChanges();
}
else
}
catch (Exception ex)
{
}
}
Normally you can not create a folder outside the root path i.e. if you have your application in say C:\inetpub\testapp you can only create a folder inside testapp. This restriction is for security reason where a web server is not supposed to allow access to anything above root folder.
Moreover it's not recommended to write any folders/files in the root folder as writing to root folder cause appdomain to recycle after certain number of writes (default is 15) causing session loss. See my answer here.
However there is a workaround
Add a path of your server to web.config and then fetch it in your code.Use something like below in the appsettings section of web.config
<add key="logfilesPath" value="C:\inetpub\MyAppLogs" />
Create a folder of above path and add Users group to your folder and give that group full permission (read/write). (Adding permission is very important)
In your code you can fetch as below
string loggerPath = (ConfigurationManager.AppSettings["logfilesPath"]);
Hope this helps

C#, Creating .txt file

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....

How to give IIS AppPool Desktop Rights

The action I need help about, is to execute a EXE file on own servers disk from a intranet-webpage, which IIS are on same server-installation. The webpage use a business layer to execute a ProcessStart together with given parameters.
When I perform the execution from web, the taskmanager show me that the application are starting up with the IIS AppPool of webpage as user. Few seconds later it's killed. In my database logs, I can see;
The Microsoft Jet database engine cannot open the file '\\computer\pathfile.ext'. It is already opened exclusively by another user, or you need permission to view its data.
That's correct. The EXE tool are, in turn, loading files from other computers. This is a special behavior which are well studied and well working while using the tool from desktop.
My goal/question,
I want this web-function-call behave with desktop rights. Is it possible at all?
The IIS AppPool have a regular setup with account ApplicationPoolIdentity. I appeared to be "lucky unwise", without knowledge about how much IIS 7.5 and Windows Server 2008 R2 raised the security model since <=IIS6.
I tried to change the app-pool user to NetworkService, Administrator.
I tried to set the application with app-pool as exec/read right
I even tried to let webapp to run a batch-file with a call to application inside..
Then I was begin to change the ProcessStart-behavior. And here, I
don't know much of what to do. I tried to add VERB runas. Force a
password prompt is not a solution here. I tried to simulate a
username/password. No luck there. I also tried to add runas /user:
blabla as parameters with ProcessStart, after used /savecred in a
desktop command window once. No luck there.
Maybe this should work but I just don't understand the correct setup of properties. I add the ProcessStart code snippet below, also added some commented code to let you see what I tried.
public string RunProcess(ApplicationType type, int param)
{
currentSelection = GetApplicationType(type);
ProcessStartInfo info = new ProcessStartInfo(currentSelection.Path);
info.CreateNoWindow = false;
info.UseShellExecute = true;
//info.UseShellExecute = false;
//info.ErrorDialog = false;
//info.UserName = "dummyUsEr";
//info.Password = this.SecurePwd("DummyPWd");
info.WindowStyle = ProcessWindowStyle.Normal;
info.Arguments = string.Format(" {0}", param.ToString());
using (Process exec = Process.Start(info))
{
try
{
exec.WaitForExit();
}
catch
{
}
}
return output;
}
EDIT
Just to be clear, and perhaps help some another guy/girl browsing to this question, I attach the snippet of Password-generation,
protected System.Security.SecureString SecurePwd(string pwd)
{
SecureString securePwd = new SecureString();
foreach (char ch in pwd.ToCharArray())
securePwd.AppendChar(ch);
return securePwd;
}
I see that you've tried putting in a specific username and password for the process start impersonation, but you say that the process accesses files on another computer and I don't see any mention of specifying a domain name which presumably you would need to access remote files?
So like this:
info.Domain = "domainname";
info.UserName = "dummyUsEr";
info.Password = "DummyPWd";
Also, what does this.SecurePwd() do and have you tried it with just the straight password string that you're passing into it?

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)

winform application to launch and read from a file with custom extension

I am building a windows forms application using C# that needs to get launched when a user clicks on a file with custom extension(eg. filename.mycustomextension)
I plan to put a url in the filename.mycustomextension file. when user clicks on this file, we winform application should launch and also read contents of this file.
Is it possible to do this?
First and most obviously you'll need to associate the file extension with the application either by "open with" in the shell, through an installer or directly in the registry.
MSDN - Best Practices for File Associations
Then from there it's really pretty simple.
static class Program
{
[STAThread]
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
string text = File.ReadAllText(args[1]);
// ...
}
}
args[0] is the application path.
args[1] will be the file path.
args[n] will be any other arguments passed in.
Offhand I can't find any examples that show all of this together simply but Scott Hanselman has a nice example of loading files through a single instance WinForms application, about the same...
http://www.hanselman.com/blog/CommentView.aspx?guid=d2f676ea-025b-4fd6-ae79-80b04a34f24c
Yes, it is possible.
The idea is that when your application is clicked, you modify the registry key, to associate the extension file with your application.
Here are the sketches:
Use the FileAssociation class from here.
Initialize it, set all the parameters.
Here is an example:
var FA = new FileAssociation();
FA.Extension = "blah";
FA.ContentType = "application/blah";
FA.FullName = "blah Project File";
FA.ProperName = "blahFile";
FA.AddCommand("open", string.Format("\"{0}\" \"%1\"", System.Reflection.Assembly.GetExecutingAssembly().Location));
//"C:\\mydir\\myprog.exe %1");
FA.IconPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
FA.IconIndex = 0;
FA.Create();
If you plan to launch your application from a browser then there are security issues, but other than that - yes.
You just need to install the application on the user's machine and associate your .mycustomextension with the application. http://support.microsoft.com/kb/185453

Categories