如何檢查寫入目錄或文件的權(quán)限?我有一個程序,使用如下所示的方法將一些數(shù)據(jù)寫入文件。public void ExportToFile(string filename){
using(FileStream fstream = new FileStream(filename,FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine(text);
}}運(yùn)行程序時出現(xiàn)錯誤:未處理的異常:System.UnauthorizedAccessException:拒絕訪問路徑'mypath'。在System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath)at System.IO.FileStream.Init(String path,F(xiàn)ileMode mode,F(xiàn)ileAccess access,nt32 rights,Boolean useRights,F(xiàn)ileShare share,Int32 bufferSize,F(xiàn)ileOptions ptions,SECURITY_ATTRIBUTES secAttrs) System.IO.FileStream..ctor中的String String msgPath,Boolean bFromProxy(字符串路徑,F(xiàn)ileMode模式,F(xiàn)ileAccess訪問FileShare共享,Int32 bufferSize,F(xiàn)ileOptions選項,字符串msgPath,Boolea bFromProxy)問題:我需要使用哪些代碼來獲取此信息以及如何授予訪問權(quán)限?
3 回答

浮云間
TA貢獻(xiàn)1829條經(jīng)驗 獲得超4個贊
當(dāng)您的代碼執(zhí)行以下操作時:
檢查當(dāng)前用戶是否有權(quán)執(zhí)行某些操作。
執(zhí)行需要檢查1中的權(quán)利的操作。
您存在權(quán)限在1和2之間變化的風(fēng)險,因為您無法預(yù)測在運(yùn)行時系統(tǒng)上還會發(fā)生什么。因此,即使您之前已經(jīng)檢查過權(quán)限,您的代碼也應(yīng)該處理拋出UnauthorisedAccessException的情況。
請注意,SecurityManager類用于檢查CAS權(quán)限,并且實際上不會檢查當(dāng)前用戶是否具有對指定位置的寫訪問權(quán)(通過ACL和ACE)。因此,對于本地運(yùn)行的應(yīng)用程序,IsGranted將始終返回true。
示例:
//1.?Provide?early?notification?that?the?user?does?not?have?permission?to?write.FileIOPermission?writePermission?=?new?FileIOPermission(FileIOPermissionAccess.Write,?filename);if(!SecurityManager.IsGranted(writePermission)){ ????//No?permission.? ????//Either?throw?an?exception?so?this?can?be?handled?by?a?calling?function ????//or?inform?the?user?that?they?do?not?have?permission?to?write?to?the?folder?and?return.}//2.?Attempt?the?action?but?handle?permission?changes.try{ ????using?(FileStream?fstream?=?new?FileStream(filename,?FileMode.Create)) ????using?(TextWriter?writer?=?new?StreamWriter(fstream)) ????{ ????????writer.WriteLine("sometext"); ????}}catch?(UnauthorizedAccessException?ex){ ????//No?permission.? ????//Either?throw?an?exception?so?this?can?be?handled?by?a?calling?function ????//or?inform?the?user?that?they?do?not?have?permission?to?write?to?the?folder?and?return.}
這很棘手,不建議嘗試以編程方式根據(jù)原始ACL(通過System.Security.AccessControl類提供的所有內(nèi)容)從文件夾中計算有效權(quán)限。
- 3 回答
- 0 關(guān)注
- 1221 瀏覽
添加回答
舉報
0/150
提交
取消