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


 

一個剛剛開始學習編程的人,如果遇到問題無法解決可能會尋找別的解決方案,如果長此以往可能會放棄這門語言而學習其他的語言...

開源與分享的重要性

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

 

1. 新建類 FileHelper

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);
}

}

}

public class FileConnect : IDisposable
{

#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("文件服務器配置錯誤");
}

}

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM