Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to run a batch file on server side in asp.net, I used the following command to execute the batch file. It's working fine when it's running in debug mode, but when I host the URL and call the batch file, it is not working.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.FileName == "")
{
Label1.Visible = true;
Label1.Text = "Browse Respective text file";
return;
}
if ((File.Exists(Server.MapPath("~/DND_BASE/" + FileUpload1.FileName))) == true)
{
Label1.Visible = true;
Label1.Text = "File Name already Uploaded";
return;
}
else
{
string DestFilepath = #"D:\124_SMS_DATA\124_SMS_Base\"+FileUpload1.FileName;
string SrcFilepath = Server.MapPath("~/DND_BASE/") + FileUpload1.FileName;
FileUpload1.SaveAs(System.IO.Path.Combine(Server.MapPath("~/DND_BASE/"), FileUpload1.FileName));
if (File.Exists(DestFilepath))
{
File.Delete(DestFilepath);
}
File.Move(SrcFilepath, DestFilepath);
Label5.Visible = true;
Label5.Text = "File Uploaded Successfully You can download file after 5 Mins";
string path = Server.MapPath(".") + "\\test.bat";
System.Diagnostics.Process.Start(path);
}
}
catch(Exception ex)
{
err = new ErrorHandler();
err.WriteToErrorLog(ex.Message.ToString());
}
}
You shouldn't run a batch file in ASP, because it runs under the permissions of the ASP user when its on a server(which for obiouse reasons is very limited) .
Your best bet is to create a scheduled job on the asp server that runs every so often and checks a folder or file that your ASP page creates or changes and then fire off events from that.
I'm not entirely sure of your goal, but please keep this in mind- The batch will run on the Local Machine. If you intend to run remotely, I'd look into Powershell. Also you will encounter several permission issues. Several batch request will require elevated permissions. Otherwise the proper way to execute a batch file from C# is like so:
using (Process.Start(#"C:\Batch\File\Location\AndName.bat"))
{
// Additional Requirements / Manipulation if Required.
}
This way it will actually dispose of the resources once your batch completes. The other alternative would be to attempt to execute the batch with elevated permissions. As I stated though before, you really should utilize Powershell as it will have access to the Windows Management Interface (WMI).
Also if you are sure about the whole batch then you'll really want to ensure you test Permissions very thoroughly. Otherwise you may encounter large errors- So familiarizing yourself with the User Access Control and ensure your Client can invoke a service to run that batch to your given machine. Be aware that you are exposing potential security issues if your data becomes malformed- As you could allow someone to alter the request to run an elevated script that is malicious.
Hopefully that at least helps.
Related
after few days of searching and investigating the problem, I finnaly decided to ask the question over here.
In the beginning I want to apologize for my english, it's not so well as it should be, so hope, you'll understand the question well :).
I have a problem when using File.Copy in ASP.NET to summarize the problem - it always says, that I don't have the permission to access the folder defined in "pathFrom". (the only way how the code works is, when I run it in my Visual Studio in debugger), after I upload it on web server, it stops working.
CODE:
protected void buttonclick(object sender, Eventargs e){
string pathFrom = "\\\\sqlSRV\\folder1\\thisOne.txt";
string pathTo = "\\\\webSRV\\folder2\\overHere.txt";
string directory = "\\\\sqlSRV\\folder2";
if (Directory.Exists(directory))
{
try
{
File.Copy(pathFrom, pathTo, true);
}
catch (FileNotFoundException)
{
Lab0.Text = "Not found.";
}
catch (FileLoadException)
{
Lab0.Text = "Cant open.";
}
}
The servers are in the same domain.
Shared folders does have ALL permissions for sqlSRV$ and webSRV$, NETWORK SERVICE, IIS_WPG even for group Everyone (just for testing right now)
we don't want to use impersonate and write the username and password into the code due to security
everything is on our LAN
running IIS10
In the old days we had similiar function in ActiveX, where it all worked (because it knew which user was running the code).
Can anyone, please, help?
Thanks a lot
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
im making an application loader which will allow you do have as many applications as you want saved in it, say for example you want to have Google Chrome in it, you press "add application" and you get an OpenFileDialog to select Chrome or any other app/program you want. the program then saves the path and name in .bin files and should load it when you click the button. it successfully loads websites but not applications, and the reason for that i think is that the program saves the file paths as
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
instead of
C:/Program Files (x86)/Google/Chrome/Application/chrome.exe
at least thats what i think. anyway here's the code for "save" and "load":
Save:
if (metroTextBox1.Text == "" || metroTextBox2.Text == "")
{
MessageBox.Show("You have to fill in both Name and Path first", "Invalid Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string[] name = { metroTextBox1.Text };
string[] path = { metroTextBox2.Text };
System.IO.File.WriteAllLines(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/appLoader/apps/appname1.bin", name);
System.IO.File.WriteAllLines(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/appLoader/apps/apppath1.bin", path);
}
Load:
try
{
string path = System.IO.File.ReadAllText(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/appLoader/apps/apppath1.bin");
Process.Start(path);
}
catch
{
}
Process.Start() can handle both, you don't have to convert any slashes or backslashes. Starting processes like this should work fine.
To hunt down the error, please check if the file exists (File.Exists(path)), if it can be run by you in Windows directly and of course (and most important) don't just catch the exception like you did but include the thrown exception like this:
catch (Exception ex) // <-- !!
{
// investigate (and log) the exception here.
// note that catching all exceptions is not a good idea so narrow
// it down once you found the exceptions you have to care for.
}
Probably the file does simply not exist or cannot be run without having a working path set (this can be mandatory for some applications).
I met a not expected problem with getting just the top directory full filenames from a specific directory. C# throws an error and doesn't list anything in the specific directory.
But MS DOS has not a problem with my command: *"dir C:\windows\prefetch\*.pf"
Visual Basics 6 old "Dir Function" also does it without complaining.
The "Windows Explorer" opens it up and doesn't ask anything from me. Also "Nirsofts Tool Suit" lists it instantly without any problem. No one of this tools needs to run with special permissions, just a double click on the application icon and ready is the task.
I looked around and found nothing here, what would answer this weird problem. My user can access the directory, if I go with any other application into it, now there is the question why C# throws
an "Unauthorized Access Exception" which is totally weird, since I have access in this folder.
I don't want to elevate my application with admin permissions for it nor create extra a xml for it to run it with highest privileges. The not trustful yellow elevation box must be avoided.
Now my question: How it comes that I can not list the filenames in this folder when all other
applications can do that.
What code do I need if "Directory.GetFiles()" fails?
Is there any flag or property in the framework directory class which allows my application access to the files, whatever.
Here my code which fails (using System.IO):
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Substring(0, 0); //clear the textBox1
//Unauthorized access exception and yellow bar in this line
foreach(string FileX in Directory.GetFiles(Path.Combine(Environment.GetEnvironmentVariable("windir"), "prefetch"), "*.pf"))
{
textBox1.Text += FileX;
}
}
Did I understand correctly that you only need the File-names with directory-names.
This code works for me, no elevations needed.
private void button1_Click(object sender, EventArgs e)
{
string folder = #"C:\windows\prefetch";
string filemask = #"*.pf";
string[] filelist = Directory.GetFiles(folder, (filemask));
//now use filelist[i] for any operations.
}
I am working on renewing an application. The old code had a main method which went through the running processes on windows and checked to see if a certain required process which is a part of the application is running, and if not it starts it. This is how it looks:
Process[] localProcesses = Process.GetProcesses(Environment.MachineName);
bool isHostAlive = false;
foreach (Process localProc in localProcesses)
{
if (localProc.ProcessName == "processIneed")
{
isHostAlive = true;
}
}
if (!isHostAlive)
{
try
{
Process.Start(Application.StartupPath + #"\bin\processIneed.exe");
}
....
Now what I did was adding an installer class in which I override the Commit method and there I'm activating the process so it will automatically run after installing the application. It looks like this:
string path = Context.Parameters["targetdir"].Replace(#"\\", #"\");
path += #"bin\processIneed.exe";
Process.Start(path);
The problem is that in the old way without activating the process during installation everything worked fine. When I'm starting the process in the new way I've implemented, I see that the path is being built correctly and the process do run in the backgroung but the application just doesn't work as it should.. It kinda "half" works.. I'm not getting any errors or exceptions but it just doesn't work.
The only difference I did notice is that with the old code the process was started under the user name which logged in to windows (user name and password entered in the login screen), while in the new code, the process starts under the user SYSTEM.
Is there a way to start the process from the installer class with the correct credentials? I want to clarify that I don't want to somehow request the password from the user and I don't want to save it or something.. just start with the currently logged on credentials and not with the SYSTEM user.
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?