I want to read files off of different windows machine on the same network, NOT part of the same domain though. (ASP.NET C# app)
Tried FileStream (can't authenticate), tried FileWebRequest (reverts to FileStream when file:/// is used), and impersonation (support.microsoft.com/kb/306158#4) Which says "impersonation failed" on my Vista.
Update: I've fixed "impersonation failed" issue. But still get "Access denied" from the other machine, even though i have "mirrored" user on both, so the question remains...
What is the right way to approach this task?
views:
1112answers:
5The only way you can do that is if the folder containing the text file is shared, and the user logged into the pc that is using your program has the permissions to access that folder.
I'm not sure if this is proper approach, but it's the way I do it. Assuming that you know a login for that computer, I P/Invoke a WNetConnection to the IPC$ object to authenticate with the machine, do my work, then do another P/Invoke to remove the connection to the IPC$.
I'm also not sure if this is the "right" way to do it, but I generally use the System.Diagnostic.Process to map a network drive using the net use command. I can then catch the success or error you would get using the Process.StandardError.ReadToEnd() or Process.StandardOutput.ReadToEnd().
http://support.microsoft.com/kb/308582
Code example:
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartiInfo.FileName = "net";
p.StartInfo.Arguments = " use " + DriveLetter + " " + "\"" + UncPath + "\"" + " " + password + " user:" + username;
p.StartInfo.UseShellExecute = false;
p.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
string errorMessage = p.StandardError.ReadToEnd();
string SuccessMessage = p.StandardOutput.ReadToEnd();
if(errorMessage != "")
{
// handle the error returned by the net command.
}
Probably not the answer you're looking for, but you asked for the right way, so... join the file server to the domain and grant ASP.NET's service account access to the share.
Try WebClient. You can use this to access a URI and I believe this includes using the 'file' protocol (or you could publish the remote file via HTTP).
You can use WebClient for a traditional download:
WebClient.DownloadFile(Uri address, string localFile)
Or return a stream:
WebClient.OpenRead(Uri address)
However your authentication issues may still remain. You can provide credentials in a standard Uri manner though may not be possible using the 'file' protocol.
I have never tried it, but I believe you can specify impersonation in the web.config
<authentication mode="Windows" />
<identity impersonate="true" username="[user]" password="[password]"/>
Though this sounds like a security risk, making your application take on the credentials of a network user rather than the anonymous user default.
More here anyway: How To: Use Impersonation and Delegation in ASP.NET 2.0