Open File on Network As A Different User - c#

I have a .NET windows application I am writing in which I want to run "explorer.exe" to open a file. Basically, I have this program that shows users files (in a grid) that is in a folder on the network in which they do not have access to. So basically I want them to be able to view certain files (like Doc(x), PDF, JPG, etc). When they click on the file in the grid, I want it to launch the appropriate application for the extension of the selected file. When using this as myself it was working using:
Process.Start("explorer.exe", #"\\myserver\folder\test.pdf");
However, these files are in a location that the actual users do not have access to. I tried wrapping it with the following:
using (new Impersonator("username", "domain", "password"))
{
}
But I got error:
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll
Additional information: Unknown error (0xfffffffe)
I even tried using ProcessStartInfo and setting username, password and domain there but kept getting:
The directory name is invalid.
So any ideas on how to launch a file (i.e. Doc(x), PDF, JPG, etc.) with giving it credentials of a user that has access to that folder on the network?

Related

Microsoft Excel cannot access the file "...". There are several possible reasons Windows Server 2008 R2 with Microsoft Office 2010

I have a problem with starting the Excel Application under a particular user.
I try to schedule this script (C#) through an application X (not Windows Task Scheduler. And this application will always use a service account to run services on the server). If I run the C# script in command prompt under the same user, it runs. Under the application X, which uses the exact same user, to initiate the C# script, it fails to open the Excel application (not sufficient permission?).
This script calls:
app.Workbooks.Open(ExcelFileName,0,false,Type.missing....), yet it gives the following error:
Microsoft Excel cannot access the file "...". There are several possible reasons:
-The file name or path does not exist.
-The file is being used by another program.
-The workbook you are trying to save has the same name as a currently open workbook.
I tried all the methods that I found online to no avail.
Create directory “C:\Windows\SysWOW64\config\systemprofile\Desktop” (for 64 bit Windows) or “C:\Windows\System32\config\systemprofile\Desktop” (for 32 bit Windows). Then Set full control permissions on Desktop directory above (for example in Win7 & IIS 7 & DefaultAppPool set permissions for user “IIS AppPool\DefaultAppPool”)
Changed the DCOM config for the Microsoft Excel application to include this user for Local/Remote Launch and Access
Enabled all macros in Excel and set the Trust Center.
Add the user to have full control on all folders that contain the Excel file.
Under DCOM config, Microsoft Excel Application, if I modify the Identity tab to check on "This User" and enter the username/password to let Excel always run under that user. Then the application runs perfectly. However, other users can't run the excel application on their own with the following error: "Cannot use object linking and embedding". If I check "Use the launching user", then Excel can't be launched. No errors in the logs or events anywhere to check.
Yet, still the same error. I think it's permission but I am not sure where and what to do for this to work.
Now, normally, when I run this excel report, I can double-click on the file and it'd automatically run, save the new parameters into the current file and generate a new excel file (with date attached to the file name). That means there is a change (save) to the original file.
I appreciate all your help!
I found the problem is the layer of security in the server!
Creating the Desktop folder inside the C:\Windows\System32\config\systemprofile and giving the service account permission to access the desktop folder is not enough.
I modified the C:\Windows\System32\config (or C:\windows\SysWOW64\config) folder to allow permission to the service account in security tab.
Then I also had to set up the same permission for the sub folder C:\Windows\System32\config\systemprofile (or C:\windows\SysWOW64\config\systemprofile) for the service account.
This works!
Microsoft Excel cannot access the file in Server 2012 Excel 2016.. checked various solutions online to create folder desktop in C:\Windows\SysWOW64\config\systemprofile\desktop.. didn't work for this but then i added a folder desktop in System32 and that definitely worked.
Since I have 64-bit Excel installed, the proper directory turned out to be the
c:\windows\system32\config\systemprofile\desktop
I ran across another way you can get this error: when you try to save a file with an "illegal" name, such as one with whacks (forward slashes) in it.
For that reason, it would seem reasonable that the err msg would give that as one possible explanation of the problem, but...no!
Specifically, I was trying to save a file named C:\RoboReporter\ABUELITOS\20160524_1327\ABUELITOS - Fill Rate - 4\1\61910B10
The whacks (shown as backwhacks in the copied exception text, but seen as forwardwhacks when hovering over the value when debugging) were the cause of the discombobulation. Once I fixed that by replacing whacks with underscores:
filename = String.Format("{0}\\{1} - Fill Rate - {2}.xlsx", uniqueFolder, _unit, _begDate.ToShortDateString());
filename = filename.Replace("/", "_");
...all went swimmingly.

File visible as normal user but not as Admin

I am building an universal updater for my company, and when I try to access a mapped network drive, the program throws a file not found exception when run as admin. When the file is run as a normal user the files are visible, but throws an Unauthorized Exception due to the fact that the files are copied to the Program Files (company policy).
Edit
The code that throws the FileNotFound Exception is FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(rdrInner.GetString(2)); and the Unauthorized Exception is thrown by File.Copy(pi.RemotePath, pi.Path, true);
Mapped drives are part of the user profile, so you need to map the drive whilst logged in as the admin user. This is why using a mapped drive is a bad idea--can't you use a fully qualified UNC path instead? See http://msdn.microsoft.com/en-gb/library/gg465305.aspx for an explanation of UNC paths.

How do I configure my ASP.NET directory to allow writing a log file?

Ok so I believe I am doing something very easy here. I have written an ASP.NET web page and it is just trying to write to the local directory.
I am using the following code:
System.IO.File.WriteAllLines("log.txt", messages);
I am throwing the following exception.
Access to the path 'c:\windows\system32\inetsrv\log.txt' is denied.
My ASP.NET application sits in the following directory.
c:\inetpub\wwwroot\sites\mysite\
So I am confused as to why it is trying to write to c:\windows\system32\inetsrv\ directory when I am not supplying that directory itself.
I have tried changing the code to the following but it gives me the same error message with a new directory.
System.IO.File.WriteAllLines("c:\\inetpub\\wwwroot\\sites\mysite\log.txt", messages);
Edit 1
It was hard to accept an answer on this because everyone really helped me out a ton. I accepted tom_yes_tom's answer because he was the first to post his response which was the first half of my problem. The other half of my problem was related to hbrock's solution that Fabio pointed out.
Create the folder "C:\inetpub\wwwroot\sites\mysite\App_Data" and save your data there instead.
System.IO.File.WriteAllLines(Server.MapPath("~/App_Data/log.txt"))
If you absolutely must save it to the mysite directory, be aware of security ramifications of putting a log file there and set directory permissions appropriately. The user that IIS is running under needs to be able to read and write that directory.
Full qualifying path: System.Web.HttpContext.Current.Server
You're receiving "Access to the path 'c:\windows\system32\inetsrv\log.txt' is denied." when you execute System.IO.File.WriteAllLines("log.txt", messages) because c:\windows\system32\inetsrv is the directory where the IIS executable is located (w3wp.exe).
You have to use Server.MapPath so it gives you the physical path of your virtual directory.
Look which user is running your virtual directory's application pool, and give him write permissions on the folder of your virtual directory.
This should help:
To grant read, write, and modify permissions to a specific file
In Windows Explorer, locate and select the required file.
Right-click the file, and then click Properties.
In the Properties dialog box, click the Security tab.
On the Security tab, examine the list of users. If the Network Service account is not listed, add it.
In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
Click Apply, and then click OK
information from: http://msdn.microsoft.com/en-us/library/ff647402.aspx#paght000015_fileaccess

Run process.start() in a network

I have written a win application that works on a network.
In one of its forms user can browse and select file from local computer and add it to a list, so the application copies these files to a folder in My Network Places that no users can access to it but one that i have created already for my application so i have his username and password.Every things works fine up to here.
In this form user can also open a file by select it and press open button, so the file should open in an application that relates to its extension(for example test.xlsx should open in Exel.exe).I have used Process.Start() to do this but for each extension i receive an individual error(for example "Access is denied" for NotePad and "RunTime error" for AdobeReader and "Not enough memory" for Excel).
What is my mistake?
Note : I have used ImpersonatUser to logon that user in my application.
Edit : I have used following code to open the file :
Using(WindowsImpersonationContext impersonateUser = LogonMethod())
{
ProcessStartInfo pInfo = new ProcessStartInfo(filePathWithExtension);
pInfo.Domain = MyDomainName;
pInfo.UseShellExecute = false;
Process.Start(pInfo);
}
Note : My LogonMethod uses LogonUser method of advapi32.dll.
The behavior you are seeing is almost expected.
it looks like you are not launching application directly, but rater using association by file name. I don't believe you'll get application launched under account you want. You can check what account application is run unrder using task manager.
Most application are not tested to run in "run as" context, so they may work correctly or fail randomly.
I could not solve this problem, so i have used another way.I have copied the file to a temp folder and then used Process.Start to open this new file.

Open/browse a password protected mapped network drive

I want to open a mapped network drive from C# code, but it is password protected, so when I try to open it directly an exception is thrown. Can someone shed light on providing a username and password while opening the this drive? Exception details:
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(String fileName)
I am just calling System.Diagnostics.Process.Start("Z:")
Z: is not a file name. [edit: it's ok if it's not password protected, tried executing your code and it worked]
Try using a ProcessStartInfo object as a parameter, as it allows setting a username and password.
And about the FileName parameter from here:
The file name is any application or document. A document is defined to be any file type that has an open or default action associated with it. You can view registered file types and their associated applications for your computer by using the Folder Options dialog box, which is available through the operating system. The Advanced button leads to a dialog box that shows whether there is an open action associated with a specific registered file type.
Perhaps you might consider instead opening the UNC path that your "z drive" is meant to point to. A reminder that a PC user can disconnect the Z: and replace it with whatever path they wanted to...
It's not entirely clear what you mean by "launch directly" and "opening this drive" but if as your code snip suggests you're trying to launch the Explorer for the drive's folder then you could use the ProcessStartInfo as a mechanism to provide credentials.
If you're trying to programmatically get access to a file(s) on that share, then you might look into the term impersonation to run your file access code blocks under a different credential. This Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials looks particularly promising.
If you're trying to actually create the network drive using pre-specified credentials then there's another solution over here - https://serverfault.com/questions/47005/specifying-username-pass-as-part-of-a-unc-path-or-map-network-drives-for-a-window/47008#47008 (don't forget to disconnect it after).

Categories