简体   繁体   English

检查 C# 中是否存在只有部分名称的文件夹

[英]Check if a folder exists with only a part of the name in C#

I have created a code to create folders with two Textboxes.我创建了一个代码来创建带有两个文本框的文件夹。

  • Textbox1 - customer number (XXXX). Textbox1 - 客户编号 (XXXX)。
  • Textbox2 - customer name. Textbox2 - 客户名称。

I would like to be able to check if the customer number exists before creating the folder.我希望能够在创建文件夹之前检查客户编号是否存在。 The newly created folder will be the combination of the two Textboxes (this is already solved).新创建的文件夹将是两个Textboxes的组合(这个已经解决了)。 I just need to be able to determine if the folder exists only with the customer number, as it is probably created with (customer number + customer name).我只需要能够确定文件夹是否仅存在客户编号,因为它可能是用(客户编号 + 客户名称)创建的。

string[] dirs = Directory.GetDirectories(@"c:\",  txtTextBox.Text + "*");

this will only get directrories starting with the desired Text这只会获得以所需文本开头的目录

Edit: This is only a good solution if the customer number has fixed places (in you exaple 4 from 0000-9999)编辑:如果客户编号有固定位置,这只是一个很好的解决方案(在您的示例 4 中,从 0000-9999)

Microsoft Documentation - check example below Microsoft 文档 - 检查下面的示例

You could also each time you need the folder just do that:您也可以在每次需要该文件夹时执行以下操作:

    public static void Main()
    {
        var username = "someuser";
        var usernumber = "ABC123";
        var mainDirectory = @"C:\Path\To\The\Main\Dir";
        var pathToTheUserDirectory = Path.Combine(mainDirectory, $"{username}-{usernumber}");

        // This line will create the directory if not exist or take the existing directory.
        var directoryInfo = Directory.CreateDirectory(pathToTheUserDirectory);

        var directoryPath = directoryInfo.FullName;

        // ...  
        // or
        // directoryInfo.Delete(recursive: true);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM