最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Windows unable to find and or remove a directory with special characters, even though it exists - Stack Overflow

programmeradmin4浏览0评论

(Please keep in mind this is my first post, I'm sorry If I'm missing important info)

Short: I have a directory (& files) that have "illegal" characters in their names. File Explorer, Windows PowerShell, and C# were all unable to purge the broken directories (Despite C# being able to create them). Using File Explorer to interact with the directories in any capacity yields the following error: "Could not find this item \n This is no longer located in PATH. Verify the items location and try again."

Long: I was writing a C# program that did some work and then wrote the results to an output location. The workload would take a pretty long time though, so I made a bunch of saves (1 per generation) incase my pc crashed, and for ease of navigation I appended the progress of the operation the generations folder name. That worked great, until I tried to delete the sessions in file explorer:

(File explorer not being able to delete the folder because it says it no longer exists)

Example of a faulty path:

Active Build (Program Working Directory)\Output\NGTS\GDP Sessions\NGTS GDP Mon-Mar-17-2025 01-14\Gen 2 (47.09%) \Details.txt

After some frustration, I asked ChatGPT how to remove the broken files (Some of those wouldn't delete either) and it recommended renaming the files and then deleting them. The Ps1 script it wrote was terrible so I made a C# tool to what it was suppose to do:

(I'm sorry about poor indentation, it was very tedious getting the code block to work as intended)

(The purge directory function is at the bottom)

    using System;
    using System.IO;
    using System.Threading;
    
    string[] RemovableFileExtensions = ["*g", "*.json", "*.txt", "*.py"];
    
    Console.ForegroundColor = ConsoleColor.White;
    string RootFaultyDirectory = Environment.CurrentDirectory;
    if (!RootFaultyDirectory.Contains(@"\NGTS") || !RootFaultyDirectory.Contains(@"\StockEngine\"))
    {
        Console.WriteLine("Refusing to purge files: Working directory might not be in a NGTS folder.\n" +
        "Aborting execution to assure no files are accidentally removed.\n" +
        $"(Directory: {RootFaultyDirectory})\n");
        
        Console.WriteLine("Press ENTER to close this window.");
        Console.ReadLine();
        Environment.Exit(-1);
    }
    
    Console.WriteLine($"Working directory: {RootFaultyDirectory}");
    Console.WriteLine("Are you sure you want to purge all training sessions.");
    string UserInput = Console.ReadLine()!.ToLower();
    if (UserInput is not ("yes" or "y"))
    {
        Console.WriteLine("User response was not \"yes\" or \"y\", closing program.");
        Thread.Sleep(1000);
        Environment.Exit(0);
    }
    
    Console.ForegroundColor = ConsoleColor.Blue;
    Console.WriteLine("\nRemoving training sessions:");
    
    try
    {
        foreach (string SearchPattern in RemovableFileExtensions)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"    Files: {SearchPattern}");
            Console.ResetColor();
            
            string[] Files = Directory.GetFiles(RootFaultyDirectory, SearchPattern, SearchOption.AllDirectories);
            foreach (string FilePath in Files)
            {
                Environment.CurrentDirectory = Path.GetDirectoryName(FilePath)! + '\\';
                
                string OldFileName = Path.GetFileName(FilePath);
                string NewFileName = OldFileName
                    .Replace('%', 'a')
                    .Replace('(', 'b')
                    .Replace(')', 'c')
                    .Replace('.', 'd')
                    + ".temp";
                
                Console.WriteLine($"        {OldFileName} --> {NewFileName}");
                
                File.Move(OldFileName, NewFileName);
                File.Delete(NewFileName);
            }
        }
        
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine($"    Folders:");
        Console.ResetColor();
        
        PurgeDirectory(Directory.GetParent(RootFaultyDirectory)!.FullName, RootFaultyDirectory);
    }
    catch (Exception Error)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(Error.ToString());
        Console.ResetColor();
        
        Console.WriteLine("Press ENTER to close this window.");
        Console.ReadLine();
        Environment.Exit(-2);
    }
    
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.WriteLine("Done.");
    Thread.Sleep(1000);
    
    static void PurgeDirectory(string ParentDirectory, string FaultyDirectory)
    {
        FaultyDirectory += '\\';
        Console.WriteLine($"        {Path.GetRelativePath(ParentDirectory, FaultyDirectory)}");
        foreach (string FaultySubDirectory in Directory.GetDirectories(FaultyDirectory, "*", SearchOption.TopDirectoryOnly))
            PurgeDirectory(FaultyDirectory, FaultySubDirectory);
    
        string OldDirectoryName = FaultyDirectory;
        string NewDirectoryName = OldDirectoryName
            .Replace('%', 'a')
            .Replace('(', 'b')
            .Replace(')', 'c')
            .Replace('.', 'd')
            .Replace('-', 'e')
            .Replace('[', 'f')
            .Replace(']', 'g')
            + " temp";
            
        Directory.Move(OldDirectoryName, NewDirectoryName);
        Directory.Delete(NewDirectoryName);
    }

I was able to rename then delete the files just fine, but the directories kept breaking it.

(C# unable to work with the directories in any capacity. (Error thrown: "DirectoryNotFoundException: Could not find a part of the path."))

In case it matters: here's the code that saves the files:

const string SaveDirectory = @"Output\NGTS\";
string GenerationalDirectory = $"{SaveDirectory}\\{OutputName} Sessions\\{SessionName}\\Gen {TrainingReport.Generation} ({Math.Round(PercentAccuracy * 100, 2)}%) {ExtraName ?? ""}{PanicName}\\";
File.WriteAllBytes(GenerationalDirectory + $"{OutputName} ({Math.Round(PercentAccuracy * 100, 2)}%) NG Binaryg", BestGraph.SerializeBinary());

[System info: Windows 11 Pro, x64 Intel] Here's a video of the issue: YouTube - Windows 11 Unable to Delete Files

Additional information requested by comments:

Path I could delete: File Explorer Full Path: D:\Stock Engine Repo\StockEngine\Latest Builds\Release\net9.0\Output\NGTS\GDP Sessions\NGTS GDP Mon-Mar-17-2025 12-19\Gen 0 (31.02%) - Details

Path I could Not delete: File Explorer Full Path: D:\Stock Engine Repo\StockEngine\Latest Builds\Release\net9.0\Output\NGTS\GDP Sessions\NGTS GDP Mon-Mar-17-2025 12-19\Gen 1 (43.8%)

Edit: Its seems like directories with a space at the end of them break the file system though I'm not 100% sure. My issue is I cant get rid of these directories because... it breaks the file system. A solution for getting rid of these directories would be appreatiated.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论