.net c# 服務器共享文件夾 windows遠程登錄 代碼

 

一個剛剛開始學習編程的人,若是遇到問題沒法解決可能會尋找別的解決方案,若是久而久之可能會放棄這門語言而學習其餘的語言...編程

開源與分享的重要性api

使用場景:將網站全部附件上傳到指定服務器的共享目錄下,首先在服務器上新建文件夾並共享 服務器

 

1. 新建類 FileHelperide

namespace Frame.FileHelper
{學習

public class FileHelper
{網站


public static void CreateFolder(string path)
{
string dirPath = path.Substring(0, path.LastIndexOf("\\"));
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}spa

}orm

}token

public class FileConnect : IDisposable
{rem

#region win32 API
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername,string lpszDomain,string lpszPassword,int dwLogonType,int dwLogonProvider,ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr existingTokenHandle,int SECURITY_IMPERSONATION_LEVEL,ref IntPtr duplicateTokenHandle);


// logon types
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT35 = 1;

WindowsIdentity newIdentity;
WindowsImpersonationContext impersonatedUser;
bool isSuccess = false;
IntPtr token = IntPtr.Zero;

public bool IsConnectted
{
get { return isSuccess; }
}

public FileConnect()
{
string fileServer = ConfigurationManager.AppSettings["FileServer"];  //遠程服務器地址 

if (!string.IsNullOrEmpty(fileServer))
{
isSuccess = Connect(fileServer, ConfigurationManager.AppSettings["FileServerUserName"], ConfigurationManager.AppSettings["FileServerPassword"]); //登陸名 密碼
}
else
{
isSuccess = true;
}
}

public bool Connect(string remoteAddr, string userName, string password)
{
bool isSuc = false;
try
{
isSuc = LogonUser(userName,remoteAddr, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);

newIdentity = new WindowsIdentity(token);
impersonatedUser = newIdentity.Impersonate();
}
catch (Exception )
{
return false;
}

return isSuc;
}

public void DisConnect()
{
if (isSuccess)
{
if (impersonatedUser != null)
impersonatedUser.Undo();
if (token != IntPtr.Zero)
CloseHandle(token);
}
}

 

public void Dispose()
{
DisConnect();
}

#endregion

}

}

---------------------------------------------

2.上傳

public string uploadFileAndThumb(HttpContext context, string paramData, params object[] param)
{

using (FileConnect connect = new FileConnect())
{
string str_Result = "";
if (!connect.IsConnectted)
{
// throw new UException("");
str_Result = "{status:'fail',info:'文件服務器配置錯誤!'}";
return str_Result;
}
 

HttpPostedFile file = context.Request.Files["FileData"]; 
string extensionName = string.Empty;
string fileName = string.Empty;
if (file.FileName.LastIndexOf(".") > 0)
{
int len = file.FileName.LastIndexOf(".");
extensionName = file.FileName.Substring(len); 

int lastIndex = file.FileName.LastIndexOf("\\");

if (lastIndex>0)
{
int subLength = len - 1 - lastIndex;
fileName = file.FileName.Substring(lastIndex+1, subLength);
}
else
{
//chorme
fileName = file.FileName.Substring(0, file.FileName.LastIndexOf("."));
}

string date = DateTime.Now.ToString("yyyyMMdd");

string pID="";
string relativePath = string.Format(@"\Project\{0}\{1}\", pID, date);
string FileFolder = System.Configuration.ConfigurationManager.AppSettings["FilePath"]; // 相似 \\10.2.183.21
string absoluteName = FileFolder + relativePath+ fileName+extensionName;
FileHelper.CreateFolder(absoluteName);

//判斷文件大小
long length = file.ContentLength;
if (length > Convert.ToInt32(param[5]))
{
return "{ status:'100100',info:'' }";
}
else
{
file.SaveAs(absoluteName);

}

}

 

-------------------------------------------

3. 在須要下載附件 的頁面 引用如下代碼,登陸遠程服務器

//登陸共享文件夾
using (FileConnect coneect = new FileConnect())
{
if (!coneect.IsConnectted)
{
// throw new UException("文件服務器配置錯誤");
}

}

 

--------------------------------------------

相關文章
相關標籤/搜索