Thursday, February 11, 2010

Accessing a Network Shared file from IIS/Local in C#

Steps To Be Followed To Open/Copy the Network Shared File
---------------------------------------------------------

1. Create a New User in Local Users and Groups by Right-clicking on MyComputer-->Manage





Create a User as Mentioned above in the System which hosts the Application and the System which shares the Files on a network.

The Username and password should be the same in both the systems.

2. Then use the below code and access the required File. The option of saving the network shared file is also available, If not you can just show the file in the same web page that requests for the File.

using System.Runtime.InteropServices;
using System.Security.Principal;
using System.IO;

public partial class PDFTest : System.Web.UI.Page
{
int LOGON32_LOGON_INTERACTIVE = 2;
int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
return true;
else
return false;
}
else
return false;
}
else
return false;
}

private void undoImpersonation()
{
impersonationContext.Undo();
}

protected void Page_Load(object sender, EventArgs e)
{
doDownload();
}

private bool doDownload()
{
try
{
string strPath = @"\\REMOTEMACHINE\SHAREDFOLDER";
bool bFileExists = false;
if (strPath.Substring(strPath.Length) != "\\")
{
strPath = strPath + "\\";
}
string strFileLocation = strPath + "FILENAME";
if (impersonateValidUser("TestAcc", Environment.MachineName, "TESTAccPASSWORD"))
{
bFileExists = System.IO.File.Exists(strFileLocation);
}
if (!bFileExists)
{
//File does not exist!
undoImpersonation();
Response.Redirect("error.aspx?m=There was an error while attempting to access the file you selected. Please re-try your download.");
return;
}
//Writing to the Same Web Page
long lCurrentPosition = 0;
int intBytesRead = 0;
FileStream objFileStream = System.IO.File.Open(strFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] arrBuffer = new byte[objFileStream.Length+20];
objFileStream.Position = lCurrentPosition;
intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
lCurrentPosition = objFileStream.Position;
objFileStream.Close();

if (arrBuffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", arrBuffer.Length.ToString());
Response.AddHeader("Content-Type", "application/pdf");
Response.BinaryWrite(arrBuffer);
//Response.End();
}


//Saving/Opening the Network PDF
//Response.ClearContent();
//Response.ClearHeaders();
//Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition", "attachment;filename=" + "sss.pdf");
//Response.AddHeader("Content-Length", new FileInfo(strFileLocation).Length.ToString());
//long lCurrentPosition = 0;
//byte[] arrBuffer = new byte[524288];
//int intBytesRead = 0;
//FileStream objFileStream = System.IO.File.Open(strFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read);
//objFileStream.Position = lCurrentPosition;
//intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
//lCurrentPosition = objFileStream.Position;
//objFileStream.Close();
//while (intBytesRead > 0 && Response.IsClientConnected)
//{
// Response.OutputStream.Write(arrBuffer, 0, intBytesRead);
// Response.Flush();
// try
// {
// objFileStream = System.IO.File.OpenRead(strFileLocation);
// objFileStream.Position = lCurrentPosition;
// intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
// lCurrentPosition = objFileStream.Position;
// }
// catch (Exception ex)
// {
// //catch puke here
// }
// finally
// {
// objFileStream.Close();
// }
//}
undoImpersonation();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}

If you find any difficulties in this code let me know..

No comments:

Post a Comment