Read file on a remote server - c#

I have a file on a remote server and I want to read this file.
lets say the files location is:
string filePath = #"\\192.168.101.15\c$\program files\xxx\test.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
This code is for sure throwing an error:
Logon failure: unknown user name or bad password.
How can I pass my credentials??
if I go start/run and put this path, I need to provide credentials lets say Admin and password 123.
Im using Asp.net, c# 3.5
Any Ideas

You have to use impersonation, ie execute your code with a user who has acces to the shared folder instead of asp.net user :
http://msdn.microsoft.com/en-us/library/aa292118%28VS.71%29.aspx
You have two way :
-with code
-with configuration

Your application will need to run as a user that has access to the UNC path, or else impersonate a user with such permissions, for the file load operation.

You'd need to be pre-authenticated on the share before you can access the files. It isn't something you can do just by passing a UNC path.
You might consider executing a net use command via the shell programatically. That's the only way I can find to do this.

Related

How to save XML file on IIS 7 server using ASP.NET

So I have a problem in my ASP.NET MVC application, it doesn't want to save the xml file after I publish it. I have a form which I post to a controller using ajax, and then I use that data to create an xml file which i then want to save.
I use the following code to generate my xml file and save it:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);
StreamWriter path = new StreamWriter(Server.MapPath("/"+ fileName + ".xml"));
xmlDoc.Save(path);
If I run my application in debug It writes the file to ~/MySolution/MyProject/MyFile, no problem.
So when I publish the app to the IIS 7 server on my computer and load the app through localhost/MyApp, I expect it to write the file to C:\inetpub\wwwroot\MyApp\MyFile but it doesn't.
I have enabled permissions to the folder inetpub and all the subsequent folders for NETWORK SERVICE. But the AJAX post keeps returning in Error and the file doesn't appear in the folder, so I assume it's not allowing to write the file to the specified path, or the path is incorrect, ether way I don't know how to check what's gone wrong.
How do I make the published app write the xml file to the C:\inetpub\wwwroot\MyApp\MyFile path?
First of all it's not recommended to write any 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 more details here.
I would suggest you to 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="filePath" value="C:\inetpub\wwwroot\MyApp" />
Regarding the permissions please add Users group to your folder and give that group full permission (read/write).
To further find out which specific user (as there are too many use cases) is used by w3wp you can use process monitor as explained below
Capture Process Monitor log while reproducing issue
Filter on Access Denied
No Access Denied, so filter on w3wp.exe
Look for access to 401-3.htm
Review entries before the 401-3.htm to determine what file was accessed last
Check permissions based on successful QuerySecurityFile operation for last file accessed (in this case was asp.dll)

Access Denied in .NET writing file to file share

I have a web service that is trying to write a file to a file share.
The application pool for the site in iis is running as a custom domain account: "domain\domainaccount"
I'm operating under the assumption and hope that when the code tries to write the file it will use the "domain\domainaccount" user to do so.
Executing the following line of code produces the error: Access to the path [filename] is denied
FileStream stream = File.Create(fileName, result.Length);
I have confirmed that the "domain\domainaccount" account has access to [filename] which is the full path of the file including the file name. I have even given the account access from the very top of the share structure, not just the specific folder the file needs to be written to. In fact, if I run notepad as "domain\domainaccount" I can save a file to that exact location.
What might I be doing incorrectly? Is it not using the domain account to write the file? If not, can I change something so that it does?
I should note that if I log into the iis server and run the web service from there, I do not get the access denied message and the file is created.

Upload file to server .Net

I am using C# .net and I am trying to upload a file to my server. I am not using asp .net.
I followed This Question and it doesn't seem to work for me. On a sidenote, this question was written back in 2008.
I am using this code as shown in the question above:
File.Copy("zQn69PZUx.png", "\\\\198.57.247.152\\~shiro\\public_html\\new");
//tried this also
File.Copy("zQn69PZUx.png", "\\\\198.57.247.152\\~shiro\\new");
The error I get:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The network path was not found.
I also tried using my domain name and use the path like it shows up in the browser, without http:// because it complained about the format, saying its not accepted, like this: domain-name.com\\new, and still got the same error as a result.
Any ideas what I could be doing wrong, or have a better solution on how to upload a file to a server ? You can see here that the http://198.57.247.152/~shiro/new/ path exists.
The path \\198.57.247.152\~shiro\new is what Microsoft calls Uniform Naming Convention (UNC). This type of resource is only available on networks with NetBIOS enabled; essentially local network. The problem is that File.Copy only works if you have access to it in your network - since this is a remote server, it won't be able to find that server, leading to the The network path was not found exception.
http://198.57.247.152/~shiro/new/ follows the syntax of <scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ] which is call Uniform resource locator (URL). Hypertext Transfer Protocol (http) resource is typical accessed by a browsers.
You can resolve this by instead using FTP to upload your file to the server:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://ftpserver.com/targetpath", "localfilepath");
}
A valid target path would be something like: ftp://localhost/samplefile.txt
and the local filepath should be the fully qualified filepath.
You can upload file using code from Peter Luu's answer. But first you should have access to it.
For uploading a file to a remote server, you should be a user of it and should have a password. It is not the password you use for logging in to your Hostgator control panel. After logging into your Hostgator account, there will be an option like FTP in it, where you can setup FTP user accounts. There you can assign a user name and password and that have to be applied to the code for uploading..
And for checking whether the UserName and Password works, Open MyComputer, and in the addressbar type the FTP path (which will be something starting "ftp://"). There pops up a Dialog asking for UserName and Password (If the path is valid). If you enter into, See and copy files into the explorer window from there, then the uploading code will work
If you want to get the applicable path, Open windows explorer and type ftp://your_domain_name. Apply UserName and Password, browse through the path you need, copy it from the address bar and add it to the code.

Network Share/SMB Client

I'm trying to read a file from a android phone to a Windows share. I'm using now the StreamWriter, like below:
StreamWriter outfile = new StreamWriter(#"\\10.16.68.253\sam\AllTxtFiles.txt");
outfile.WriteLine("TESTGENREOIADNIWAN");
But i get a Access Denied. I already added the permission to the manifest. And i tested the share using the ES File Explorer (with everyone access). I used the same lines of code on a WPF app and works fine, so my problem is in Android app.
I already tried to change the connection string like the ES, smb://10.16.68.253/sam/AllTxtFiles.txt, but no luck.
Anyone accomplished this ?
Tks !
for me I had to set up the string like this "smb://username:password#local ip/" for the root of my server's Windows share.
You have to make sure the connection to the SMB share is authenticated before trying to access any files. You have to use API calls to do this, because this stuff is done in the Win32 layer outside of managed code.
Here's a start:
http://www.pinvoke.net/default.aspx/mpr/WNetAddConnection.html
Are you sure you are able to read/write files using ESFileExplorer with EVERYONE ACCESS permissions?
Windows is a very secured OS. You need to grant permissions to a particular profile.
Example:
Create a new profile name on windows.
Give that new profile name a password. (must have a password to share something)
Give the folder or files permission to share access to that profile with password.
Access the folder or files using smb along with the profile username and password. Such as
"smb://username:password#local ip"
StreamWriter outfile = new StreamWriter(smb:\\username:password#"\\10.16.68.253\sam\AllTxtFiles.txt");
outfile.WriteLine("TESTGENREOIADNIWAN");

Programatically grant access permission to user in C:\ to create textfiles

I ran my program in C# that suppose to create and write a file in C:\, but an error occurred saying that access to the path C:\mytextfile.txt is denied. Is there any code that will give the user permission in C:\?
Yes by using the manifest http://www.codeproject.com/Articles/66259/Requesting-Admin-Approval-at-Application-Start or run as different account which has sufficient rights
You need to run the code as an administrator. You don't need C# code for this, you need to change how you're running the code.
However, I suspect that you're trying to do something wrong. I'd guess that you're trying to store some data locally, and are using the root of C: for simplicity, when you should actually be using the standard libraries to locate the users folder or to get a temporary file.
e.g. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
(for other folders, use Intellisense to look at the other SpecialFolder children.)

Categories

Resources