在我的.NET 2.0应用程序中,我需要检查是否有足够的权限来创建和写入目录的文件.为此,我有以下函数尝试创建一个文件并向其写入一个字节,然后删除自己以测试权限是否存在.
我认为检查的最佳方法是实际尝试并执行此操作,捕获发生的任何异常.虽然我对一般的异常捕获并不是特别高兴,所以有更好的或者更可接受的方式吗?
private const string TEMP_FILE = "\\tempFile.tmp";
/// <summary>
/// Checks the ability to create and write to a file in the supplied directory.
/// </summary>
/// <param name="directory">String representing the directory path to check.</param>
/// <returns>True if successful; otherwise false.</returns>
private static bool CheckDirectoryAccess(string directory)
{
bool success = false;
string fullPath = directory + TEMP_FILE;
if (Directory.Exists(directory))
{
try
{
using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew,
FileAccess.Write))
{
fs.WriteByte(0xff);
}
if (File.Exists(fullPath))
{
File.Delete(fullPath);
success …Run Code Online (Sandbox Code Playgroud) 我有一个程序,使用如下所示的方法将一些数据写入文件.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
运行程序时出现错误:
未处理的异常:System.UnauthorizedAccessException:拒绝访问路径'mypath'.在System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath)at System.IO.FileStream.Init(String path,FileMode mode,FileAccess access,nt32 rights,Boolean useRights,FileShare share,Int32 bufferSize,FileOptions ptions,SECURITY_ATTRIBUTES secAttrs) System.IO.FileStream..ctor中的String String msgPath,Boolean bFromProxy(字符串路径,FileMode模式,FileAccess访问FileShare共享,Int32 bufferSize,FileOptions选项,字符串msgPath,Boolea bFromProxy)
问题:我需要使用哪些代码来获取此信息以及如何授予访问权限?
我是编程的新手,并且只使用用C#编写的标准控制台程序.
我目前正在实习,我被要求为他们设计一个小工具.
公平地说,这项任务远远超过我的前进,而且与我以前用C#所做的完全不同.
该工具基本上必须执行以下操作:
用户选择要搜索的文件夹.
程序检查文件夹和所有子文件夹中的所有文件,如果尚未选中则检查写保护.
如果当前没有,程序会在所有文件上设置只读属性.
如果这不是寻求帮助的地方,请忽略我的问题.
谢谢阅读.