相关疑难解决方法(0)

检查.NET中的目录和文件写入权限

在我的.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)

.net c# directory file-permissions winforms

75
推荐指数
5
解决办法
11万
查看次数

以递归方式搜索目录中的文件

我有以下代码通过目录递归搜索文件,该目录返回所有xml文件的列表给我.一切正常,但根目录中的xml文件不包含在列表中.

我理解为什么,因为它首先做的是获取根目录中的目录,然后获取文件,从而错过了根目录上的GetFiles()调用.我尝试在foreach之前包含GetFiles()调用,但结果并不像我预期的那样.

public static ArrayList DirSearch(string sDir)
{
    try
    {
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string f in Directory.GetFiles(d, "*.xml"))
            {
                string extension = Path.GetExtension(f);
                if (extension != null && (extension.Equals(".xml")))
                {
                fileList.Add(f);
                }
            }
            DirSearch(d);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return fileList;
}
Run Code Online (Sandbox Code Playgroud)

我的目录结构类似于:

RootDirectory
        test1.0.xml
            test1.1.xml
            test1.2.xml
  2ndLevDir
            test2.0.xml
            test2.1.xml
  3rdLevDir
               test3.0.xml
               test3.1.xml
Run Code Online (Sandbox Code Playgroud)

代码返回:

test2.0.xml
test2.1.xml
test3.0.xml
test3.1.xml
Run Code Online (Sandbox Code Playgroud)

我想返回每个文件,包括:

test1.0.xml
test1.1.xml
test1.2.xml
Run Code Online (Sandbox Code Playgroud)

不太适用于递归.任何指针都将非常感激.

c# recursion

57
推荐指数
2
解决办法
13万
查看次数

标签 统计

c# ×2

.net ×1

directory ×1

file-permissions ×1

recursion ×1

winforms ×1