Modo migliore per verificare se un percorso è un file o una directory?


383

Sto elaborando una TreeViewdirectory e file. Un utente può selezionare un file o una directory e quindi fare qualcosa con esso. Ciò richiede che io abbia un metodo che esegue diverse azioni in base alla selezione dell'utente.

Al momento sto facendo qualcosa del genere per determinare se il percorso è un file o una directory:

bool bIsFile = false;
bool bIsDirectory = false;

try
{
    string[] subfolders = Directory.GetDirectories(strFilePath);

    bIsDirectory = true;
    bIsFile = false;
}
catch(System.IO.IOException)
{
    bIsFolder = false;
    bIsFile = true;
}

Non posso fare a meno di sentire che esiste un modo migliore per farlo! Speravo di trovare un metodo .NET standard per gestirlo, ma non sono stato in grado di farlo. Esiste un metodo del genere e, in caso contrario, qual è il mezzo più semplice per determinare se un percorso è un file o una directory?


8
Qualcuno può modificare il titolo della domanda per specificare il file / la directory "esistente" ? Tutte le risposte si applicano a un percorso per un file / directory che si trova sul disco.
Jake Berger,

1
@jberger si prega di fare riferimento alla mia risposta di seguito. Ho trovato un modo per ottenere ciò per percorsi di file / cartelle che potrebbero esistere o meno.
lhan,


Come stai popolando questa treeview? Come riesci a uscirne?
Casuale 832

Risposte:


596

Da Come sapere se il percorso è un file o una directory :

// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:\Temp");

//detect whether its a directory or file
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");

Aggiornamento per .NET 4.0+

Per i commenti seguenti, se si utilizza .NET 4.0 o versioni successive (e le prestazioni massime non sono critiche) è possibile scrivere il codice in modo più pulito:

// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:\Temp");

if (attr.HasFlag(FileAttributes.Directory))
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");

8
+1 Questo è l'approccio migliore ed è significativamente più veloce della soluzione che ho proposto.
Andrew Hare,

6
@ KeyMs92 È matematica bit per bit. Fondamentalmente, attr è un valore binario con un bit che significa "questa è una directory". Bitwise e &operator restituiranno un valore binario in cui sono attivati ​​solo i bit che sono attivi (1) in entrambi gli operandi. In questo caso, eseguendo un'operazione bit a bit e contro attre il FileAttributes.Directoryvalore restituirà il valore di FileAttributes.Directoryse il bit dell'attributo del file Directory è attivato. Vedi en.wikipedia.org/wiki/Bitwise_operation per una spiegazione migliore.
Kyle Trauberman,

6
@jberger Se il percorso non esiste, è ambiguo se si C:\Tempriferisce a una directory chiamata Tempo a un file chiamato Temp. Cosa significa fare il codice?
ta.speot.is

26
@Key: dopo .NET 4.0, attr.HasFlag(FileAttributes.Directory)può essere utilizzato invece.
Şafak Gür,

13
@ ŞafakGür: non farlo all'interno di un ciclo sensibile al tempo. attr.HasFlag () è lento come l'inferno e usa Reflection per ogni chiamata
springy76

247

Che ne dici di usarli?

File.Exists();
Directory.Exists();

43
Ciò ha anche il vantaggio di non generare un'eccezione su un percorso non valido, a differenza File.GetAttributes().
Deanna,

Uso la libreria Long Path da BCL bcl.codeplex.com/… nel mio progetto, quindi non c'è modo di ottenere gli attributi di file ma chiamare Exist è una bella soluzione.
Puterdo Borato,

4
@jberger Mi aspetterei che NON funzioni per i percorsi di file / cartelle inesistenti. File.Exists ("c: \\ temp \\ nonexistant.txt") dovrebbe restituire false, così come è.
michaelkoss,

12
Se sei preoccupato per file / cartelle inesistenti, prova questo public static bool? IsDirectory(string path){ if (Directory.Exists(path)) return true; // is a directory else if (File.Exists(path)) return false; // is a file else return null; // is a nothing }
Dustin Townsend,

1
Maggiori dettagli su questo sono su msdn.microsoft.com/en-us/library/…
Moji

20

Con solo questa linea puoi ottenere se un percorso è una directory o un file:

File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory)

4
Ricorda che hai bisogno di almeno .NET 4.0 per questo. Anche questo esploderà se path non è un percorso valido.
nawfal,

Utilizzare un oggetto FileInfo per verificare l'esistenza del percorso: FileInfo pFinfo = new FileInfo (FList [0]); if (pFinfo.Exists) {if (File.GetAttributes (FList [0]). HasFlag (FileAttributes.Directory)) {}}. Questo funziona per me.
Michael Stimson,

Se hai già creato un oggetto FileInfo e stai utilizzando la proprietà Exists dell'istanza, perché non accedere alla sua proprietà Attributes invece di utilizzare il metodo statico File.GetAttributes ()?
dynamichael,

10

Ecco il mio:

    bool IsPathDirectory(string path)
    {
        if (path == null) throw new ArgumentNullException("path");
        path = path.Trim();

        if (Directory.Exists(path)) 
            return true;

        if (File.Exists(path)) 
            return false;

        // neither file nor directory exists. guess intention

        // if has trailing slash then it's a directory
        if (new[] {"\\", "/"}.Any(x => path.EndsWith(x)))
            return true; // ends with slash

        // if has extension then its a file; directory otherwise
        return string.IsNullOrWhiteSpace(Path.GetExtension(path));
    }

È simile alle risposte degli altri ma non è esattamente lo stesso.


3
Tecnicamente dovresti usare Path.DirectorySeparatorCharePath.AltDirectorySeparatorChar
drzaus il

1
Questa idea di indovinare l'intento è interessante. IMHO è meglio dividere in due metodi. Il metodo 1 esegue i test di esistenza, restituendo un valore booleano nullable. Se il chiamante desidera quindi la parte "indovinare", su un risultato nullo da Uno, quindi chiama il Metodo Due, che fa l'ipotesi.
ToolmakerSteve

2
Riscriverei questo per restituire una tupla con se indovinato o no.
Ronnie Overby,

1
"se ha estensione, allora è un file" - questo non è vero. Un file non deve avere un'estensione (anche in Windows) e una directory può avere un'estensione. Ad esempio, questo può essere un file o una directory: "C: \ New folder.log"
bytedev

2
@bytedev Lo so, ma a quel punto della funzione, il codice sta indovinando l'intenzione. C'è anche un commento che lo dice. La maggior parte dei file ha un'estensione. La maggior parte delle directory non lo fanno.
Ronnie Overby,

7

In alternativa a Directory.Exists (), è possibile utilizzare il metodo File.GetAttributes () per ottenere gli attributi di un file o di una directory, in modo da poter creare un metodo di supporto come questo:

private static bool IsDirectory(string path)
{
    System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
    return (fa & FileAttributes.Directory) != 0;
}

È inoltre possibile considerare l'aggiunta di un oggetto alla proprietà tag del controllo TreeView quando si popola il controllo che contiene metadati aggiuntivi per l'elemento. Ad esempio, è possibile aggiungere un oggetto FileInfo per i file e un oggetto DirectoryInfo per le directory e quindi testare il tipo di elemento nella proprietà tag per salvare le chiamate di sistema aggiuntive per ottenere quei dati quando si fa clic sull'elemento.


2
come è diverso dall'altra risposta
Jake Berger,

6
Piuttosto che quell'orribile blocco di logica, provaisDirectory = (fa & FileAttributes.Directory) != 0);
Immortal Blue,

5

Questo è stato il massimo che ho potuto inventare dato il comportamento delle proprietà Exists and Attributes:

using System.IO;

public static class FileSystemInfoExtensions
{
    /// <summary>
    /// Checks whether a FileInfo or DirectoryInfo object is a directory, or intended to be a directory.
    /// </summary>
    /// <param name="fileSystemInfo"></param>
    /// <returns></returns>
    public static bool IsDirectory(this FileSystemInfo fileSystemInfo)
    {
        if (fileSystemInfo == null)
        {
            return false;
        }

        if ((int)fileSystemInfo.Attributes != -1)
        {
            // if attributes are initialized check the directory flag
            return fileSystemInfo.Attributes.HasFlag(FileAttributes.Directory);
        }

        // If we get here the file probably doesn't exist yet.  The best we can do is 
        // try to judge intent.  Because directories can have extensions and files
        // can lack them, we can't rely on filename.
        // 
        // We can reasonably assume that if the path doesn't exist yet and 
        // FileSystemInfo is a DirectoryInfo, a directory is intended.  FileInfo can 
        // make a directory, but it would be a bizarre code path.

        return fileSystemInfo is DirectoryInfo;
    }
}

Ecco come viene testato:

    [TestMethod]
    public void IsDirectoryTest()
    {
        // non-existing file, FileAttributes not conclusive, rely on type of FileSystemInfo
        const string nonExistentFile = @"C:\TotallyFakeFile.exe";

        var nonExistentFileDirectoryInfo = new DirectoryInfo(nonExistentFile);
        Assert.IsTrue(nonExistentFileDirectoryInfo.IsDirectory());

        var nonExistentFileFileInfo = new FileInfo(nonExistentFile);
        Assert.IsFalse(nonExistentFileFileInfo.IsDirectory());

        // non-existing directory, FileAttributes not conclusive, rely on type of FileSystemInfo
        const string nonExistentDirectory = @"C:\FakeDirectory";

        var nonExistentDirectoryInfo = new DirectoryInfo(nonExistentDirectory);
        Assert.IsTrue(nonExistentDirectoryInfo.IsDirectory());

        var nonExistentFileInfo = new FileInfo(nonExistentDirectory);
        Assert.IsFalse(nonExistentFileInfo.IsDirectory());

        // Existing, rely on FileAttributes
        const string existingDirectory = @"C:\Windows";

        var existingDirectoryInfo = new DirectoryInfo(existingDirectory);
        Assert.IsTrue(existingDirectoryInfo.IsDirectory());

        var existingDirectoryFileInfo = new FileInfo(existingDirectory);
        Assert.IsTrue(existingDirectoryFileInfo.IsDirectory());

        // Existing, rely on FileAttributes
        const string existingFile = @"C:\Windows\notepad.exe";

        var existingFileDirectoryInfo = new DirectoryInfo(existingFile);
        Assert.IsFalse(existingFileDirectoryInfo.IsDirectory());

        var existingFileFileInfo = new FileInfo(existingFile);
        Assert.IsFalse(existingFileFileInfo.IsDirectory());
    }

5

Dopo aver combinato i suggerimenti delle altre risposte, mi sono reso conto di aver trovato la stessa cosa della risposta di Ronnie Overby . Ecco alcuni test per evidenziare alcune cose a cui pensare:

  1. le cartelle possono avere "estensioni": C:\Temp\folder_with.dot
  2. i file non possono terminare con un separatore di directory (barra)
  3. Esistono tecnicamente due separatori di directory che sono specifici della piattaforma, ovvero possono essere o meno barre ( Path.DirectorySeparatorChare Path.AltDirectorySeparatorChar)

Test (Linqpad)

var paths = new[] {
    // exists
    @"C:\Temp\dir_test\folder_is_a_dir",
    @"C:\Temp\dir_test\is_a_dir_trailing_slash\",
    @"C:\Temp\dir_test\existing_folder_with.ext",
    @"C:\Temp\dir_test\file_thats_not_a_dir",
    @"C:\Temp\dir_test\notadir.txt",
    // doesn't exist
    @"C:\Temp\dir_test\dne_folder_is_a_dir",
    @"C:\Temp\dir_test\dne_folder_trailing_slash\",
    @"C:\Temp\dir_test\non_existing_folder_with.ext",
    @"C:\Temp\dir_test\dne_file_thats_not_a_dir",
    @"C:\Temp\dir_test\dne_notadir.txt",        
};

foreach(var path in paths) {
    IsFolder(path/*, false*/).Dump(path);
}

risultati

C:\Temp\dir_test\folder_is_a_dir
  True 
C:\Temp\dir_test\is_a_dir_trailing_slash\
  True 
C:\Temp\dir_test\existing_folder_with.ext
  True 
C:\Temp\dir_test\file_thats_not_a_dir
  False 
C:\Temp\dir_test\notadir.txt
  False 
C:\Temp\dir_test\dne_folder_is_a_dir
  True 
C:\Temp\dir_test\dne_folder_trailing_slash\
  True 
C:\Temp\dir_test\non_existing_folder_with.ext
  False (this is the weird one)
C:\Temp\dir_test\dne_file_thats_not_a_dir
  True 
C:\Temp\dir_test\dne_notadir.txt
  False 

Metodo

/// <summary>
/// Whether the <paramref name="path"/> is a folder (existing or not); 
/// optionally assume that if it doesn't "look like" a file then it's a directory.
/// </summary>
/// <param name="path">Path to check</param>
/// <param name="assumeDneLookAlike">If the <paramref name="path"/> doesn't exist, does it at least look like a directory name?  As in, it doesn't look like a file.</param>
/// <returns><c>True</c> if a folder/directory, <c>false</c> if not.</returns>
public static bool IsFolder(string path, bool assumeDneLookAlike = true)
{
    // /programming/1395205/better-way-to-check-if-path-is-a-file-or-a-directory
    // turns out to be about the same as https://stackoverflow.com/a/19596821/1037948

    // check in order of verisimilitude

    // exists or ends with a directory separator -- files cannot end with directory separator, right?
    if (Directory.Exists(path)
        // use system values rather than assume slashes
        || path.EndsWith("" + Path.DirectorySeparatorChar)
        || path.EndsWith("" + Path.AltDirectorySeparatorChar))
        return true;

    // if we know for sure that it's an actual file...
    if (File.Exists(path))
        return false;

    // if it has an extension it should be a file, so vice versa
    // although technically directories can have extensions...
    if (!Path.HasExtension(path) && assumeDneLookAlike)
        return true;

    // only works for existing files, kinda redundant with `.Exists` above
    //if( File.GetAttributes(path).HasFlag(FileAttributes.Directory) ) ...; 

    // no idea -- could return an 'indeterminate' value (nullable bool)
    // or assume that if we don't know then it's not a folder
    return false;
}

Path.DirectorySeparatorChar.ToString()invece di string concat con ""?
Codice finito il

@GoneCoding probabilmente; all'epoca stavo lavorando con un sacco di proprietà nullable quindi mi sono preso l'abitudine di "concat con stringa vuota" piuttosto che preoccuparmi di verificare la presenza di null. Potresti anche fare new String(Path.DirectorySeparatorChar, 1)quello che è ToString, se vuoi essere davvero ottimizzato.
drzaus,

4

L'approccio più accurato utilizzerà un codice di interoperabilità da shlwapi.dll

[DllImport(SHLWAPI, CharSet = CharSet.Unicode)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool PathIsDirectory([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);

Lo chiameresti così:

#region IsDirectory
/// <summary>
/// Verifies that a path is a valid directory.
/// </summary>
/// <param name="path">The path to verify.</param>
/// <returns><see langword="true"/> if the path is a valid directory; 
/// otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <para><paramref name="path"/> is <see langword="null"/>.</para>
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <para><paramref name="path"/> is <see cref="F:System.String.Empty">String.Empty</see>.</para>
/// </exception>
public static bool IsDirectory(string path)
{
    return PathIsDirectory(path);
}

31
Brutto. Odio l'interoperare per fare questi semplici compiti. E non è portatile. ed è brutto. Ho detto che è brutto? :)
Ignacio Soler Garcia,

5
@SoMoS Potrebbe essere "brutto" secondo te, ma è ancora l'approccio più accurato. Sì, non è una soluzione portatile ma non era questa la domanda.
Scott Dorman,

8
Cosa intendi esattamente con preciso? Fornisce gli stessi risultati della risposta di Quinn Wilson e richiede l'interoperabilità che rompe la portabilità. Per me è accurato come le altre soluzioni e ha effetti collaterali che altri no.
Ignacio Soler Garcia,

7
C'è un'API Framework per farlo. L'uso di Interop non è la strada da percorrere.
TomXP411,

5
Sì, funziona, ma NON è la soluzione "più accurata", non più che usare l'attuale .NET Framework. Invece, prendi 6 righe di codice per sostituire ciò che può essere fatto in una riga con .NET Framework e ti blocchi nell'usare solo Windows, invece di lasciare aperta la possibilità di portarlo con il Mono Project. Non usare mai Interop quando .NET Framework offre una soluzione più elegante.
Russ

2

Ecco cosa usiamo:

using System;

using System.IO;

namespace crmachine.CommonClasses
{

  public static class CRMPath
  {

    public static bool IsDirectory(string path)
    {
      if (path == null)
      {
        throw new ArgumentNullException("path");
      }

      string reason;
      if (!IsValidPathString(path, out reason))
      {
        throw new ArgumentException(reason);
      }

      if (!(Directory.Exists(path) || File.Exists(path)))
      {
        throw new InvalidOperationException(string.Format("Could not find a part of the path '{0}'",path));
      }

      return (new System.IO.FileInfo(path).Attributes & FileAttributes.Directory) == FileAttributes.Directory;
    } 

    public static bool IsValidPathString(string pathStringToTest, out string reasonForError)
    {
      reasonForError = "";
      if (string.IsNullOrWhiteSpace(pathStringToTest))
      {
        reasonForError = "Path is Null or Whitespace.";
        return false;
      }
      if (pathStringToTest.Length > CRMConst.MAXPATH) // MAXPATH == 260
      {
        reasonForError = "Length of path exceeds MAXPATH.";
        return false;
      }
      if (PathContainsInvalidCharacters(pathStringToTest))
      {
        reasonForError = "Path contains invalid path characters.";
        return false;
      }
      if (pathStringToTest == ":")
      {
        reasonForError = "Path consists of only a volume designator.";
        return false;
      }
      if (pathStringToTest[0] == ':')
      {
        reasonForError = "Path begins with a volume designator.";
        return false;
      }

      if (pathStringToTest.Contains(":") && pathStringToTest.IndexOf(':') != 1)
      {
        reasonForError = "Path contains a volume designator that is not part of a drive label.";
        return false;
      }
      return true;
    }

    public static bool PathContainsInvalidCharacters(string path)
    {
      if (path == null)
      {
        throw new ArgumentNullException("path");
      }

      bool containedInvalidCharacters = false;

      for (int i = 0; i < path.Length; i++)
      {
        int n = path[i];
        if (
            (n == 0x22) || // "
            (n == 0x3c) || // <
            (n == 0x3e) || // >
            (n == 0x7c) || // |
            (n  < 0x20)    // the control characters
          )
        {
          containedInvalidCharacters = true;
        }
      }

      return containedInvalidCharacters;
    }


    public static bool FilenameContainsInvalidCharacters(string filename)
    {
      if (filename == null)
      {
        throw new ArgumentNullException("filename");
      }

      bool containedInvalidCharacters = false;

      for (int i = 0; i < filename.Length; i++)
      {
        int n = filename[i];
        if (
            (n == 0x22) || // "
            (n == 0x3c) || // <
            (n == 0x3e) || // >
            (n == 0x7c) || // |
            (n == 0x3a) || // : 
            (n == 0x2a) || // * 
            (n == 0x3f) || // ? 
            (n == 0x5c) || // \ 
            (n == 0x2f) || // /
            (n  < 0x20)    // the control characters
          )
        {
          containedInvalidCharacters = true;
        }
      }

      return containedInvalidCharacters;
    }

  }

}

2

Mi sono imbattuto in questo quando ho riscontrato un problema simile, tranne per il fatto che dovevo verificare se un percorso è per un file o una cartella quando quel file o quella cartella potrebbe non esistere realmente . Ci sono stati alcuni commenti sulle risposte sopra menzionate che non avrebbero funzionato per questo scenario. Ho trovato una soluzione (utilizzo VB.NET, ma puoi convertirla se necessario) che sembra funzionare bene per me:

Dim path As String = "myFakeFolder\ThisDoesNotExist\"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns True

Dim path As String = "myFakeFolder\ThisDoesNotExist\File.jpg"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns False

Spero che questo possa essere utile a qualcuno!


1
hai provato il metodo Path.HasExtension ?
Jake Berger

Se non esiste, non è un file o una directory. Qualsiasi nome può essere creato come uno dei due. Se hai intenzione di crearlo, allora dovresti saperlo cosa stai creando e, in caso contrario, perché potresti aver bisogno di queste informazioni?
Casuale 832

8
Una cartella può essere nominata test.txte un file può essere nominato test- in questi casi il codice restituirebbe risultati errati
Stephan Bauer,

2
Esiste un metodo .Exists nelle classi System.IO.FIle e System.IO.Directory. questa è la cosa da fare. Le directory possono avere estensioni; Lo vedo spesso.
TomXP411

2

lo so fino a tardi nel gioco, ma ho pensato di condividerlo comunque. Se stai lavorando esclusivamente con i percorsi come stringhe, capire questo è facile come una torta:

private bool IsFolder(string ThePath)
{
    string BS = Path.DirectorySeparatorChar.ToString();
    return Path.GetDirectoryName(ThePath) == ThePath.TrimEnd(BS.ToCharArray());
}

per esempio: ThePath == "C:\SomeFolder\File1.txt"finirebbe per essere questo:

return "C:\SomeFolder" == "C:\SomeFolder\File1.txt" (FALSE)

Un altro esempio: ThePath == "C:\SomeFolder\"finirebbe per essere questo:

return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)

E questo funzionerebbe anche senza la barra rovesciata finale: ThePath == "C:\SomeFolder"finirebbe per essere questo:

return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)

Tieni presente che questo funziona solo con i percorsi stessi e non con la relazione tra il percorso e il "disco fisico" ... quindi non può dirti se il percorso / file esiste o qualcosa del genere, ma è sicuro posso dirti se il percorso è una cartella o un file ...


2
Non funziona System.IO.FileSystemWatcherdal momento che quando una directory viene eliminata, viene inviata c:\my_directorycome argomento che è uguale quando c:\my_directoryviene eliminata un'estensione meno file .
Ray Cheng,

GetDirectoryName('C:\SomeFolder')ritorna 'C:\', quindi il tuo ultimo caso non funziona. Ciò non distingue tra directory e file senza estensioni.
Lucy,

Si assume erroneamente che un percorso di directory includerà sempre il "\" finale. Ad esempio, Path.GetDirectoryName("C:\SomeFolder\SomeSubFolder")tornerà C:\SomeFolder. Si noti che i propri esempi di ciò che GetDirectoryName restituisce mostrano che restituisce un percorso che non termina in una barra rovesciata. Ciò significa che se qualcuno utilizza GetDirectoryName altrove per ottenere un percorso di directory e quindi lo inserisce nel metodo, otterrà la risposta errata.
ToolmakerSteve

1

Se si desidera trovare directory, comprese quelle contrassegnate come "nascosto" e "sistema", provare questo (richiede .NET V4):

FileAttributes fa = File.GetAttributes(path);
if(fa.HasFlag(FileAttributes.Directory)) 

1

Ne avevo bisogno, i post mi hanno aiutato, questo lo porta a una riga, e se il percorso non è affatto un percorso, ritorna ed esce dal metodo. Affronta tutte le preoccupazioni di cui sopra, non ha nemmeno bisogno della barra finale.

if (!Directory.Exists(@"C:\folderName")) return;

0

Uso quanto segue, verifica anche l'estensione, il che significa che può essere utilizzato per verificare se il percorso fornito è un file ma un file che non esiste.

private static bool isDirectory(string path)
{
    bool result = true;
    System.IO.FileInfo fileTest = new System.IO.FileInfo(path);
    if (fileTest.Exists == true)
    {
        result = false;
    }
    else
    {
        if (fileTest.Extension != "")
        {
            result = false;
        }
    }
    return result;
}

1
FileInfo Extension è (IMAO) una buona opzione per controllare i percorsi inesistenti
dataCore

2
la tua seconda condizione (altro) è maleodorante. se non è un file esistente, allora non sai cosa potrebbe essere (le directory possono terminare anche con qualcosa come ".txt").
nawfal,

0
using System;
using System.IO;
namespace FileOrDirectory
{
     class Program
     {
          public static string FileOrDirectory(string path)
          {
               if (File.Exists(path))
                    return "File";
               if (Directory.Exists(path))
                    return "Directory";
               return "Path Not Exists";
          }
          static void Main()
          {
               Console.WriteLine("Enter The Path:");
               string path = Console.ReadLine();
               Console.WriteLine(FileOrDirectory(path));
          }
     }
}

0

Usando la risposta selezionata su questo post, ho guardato i commenti e ho dato credito a @ ŞafakGür, @Anthony e @Quinn Wilson per i loro bit informativi che mi hanno portato a questa risposta migliorata che ho scritto e testato:

    /// <summary>
    /// Returns true if the path is a dir, false if it's a file and null if it's neither or doesn't exist.
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static bool? IsDirFile(this string path)
    {
        bool? result = null;

        if(Directory.Exists(path) || File.Exists(path))
        {
            // get the file attributes for file or directory
            var fileAttr = File.GetAttributes(path);

            if (fileAttr.HasFlag(FileAttributes.Directory))
                result = true;
            else
                result = false;
        }

        return result;
    }

Sembra un po 'dispendioso verificare gli attributi dopo aver già verificato l'esistenza di Directory / File ()? Queste due chiamate da sole fanno tutto il lavoro necessario qui.
Codice finito il

0

Forse per UWP C #

public static async Task<IStorageItem> AsIStorageItemAsync(this string iStorageItemPath)
    {
        if (string.IsNullOrEmpty(iStorageItemPath)) return null;
        IStorageItem storageItem = null;
        try
        {
            storageItem = await StorageFolder.GetFolderFromPathAsync(iStorageItemPath);
            if (storageItem != null) return storageItem;
        } catch { }
        try
        {
            storageItem = await StorageFile.GetFileFromPathAsync(iStorageItemPath);
            if (storageItem != null) return storageItem;
        } catch { }
        return storageItem;
    }

0

Vedo, sono 10 anni troppo tardi per la festa. Stavo affrontando la situazione, dove da alcune proprietà posso ricevere un nome file o un percorso file completo. Se non viene fornito alcun percorso, devo verificare l'esistenza del file collegando un percorso di directory "globale" fornito da un'altra proprietà.

Nel mio caso

var isFileName = System.IO.Path.GetFileName (str) == str;

ha fatto il trucco. Ok, non è magico, ma forse questo potrebbe far risparmiare a qualcuno qualche minuto per capire. Dato che si tratta semplicemente di un'analisi delle stringhe, i nomi Dir con punti possono dare falsi positivi ...


0

Molto tardi alla festa qui, ma ho trovato il Nullable<Boolean>valore di ritorno abbastanza brutto - il IsDirectory(string path)ritorno nullnon equivale a un percorso inesistente senza commenti dettagliati, quindi ho trovato quanto segue:

public static class PathHelper
{
    /// <summary>
    /// Determines whether the given path refers to an existing file or directory on disk.
    /// </summary>
    /// <param name="path">The path to test.</param>
    /// <param name="isDirectory">When this method returns, contains true if the path was found to be an existing directory, false in all other scenarios.</param>
    /// <returns>true if the path exists; otherwise, false.</returns>
    /// <exception cref="ArgumentNullException">If <paramref name="path"/> is null.</exception>
    /// <exception cref="ArgumentException">If <paramref name="path"/> equals <see cref="string.Empty"/></exception>
    public static bool PathExists(string path, out bool isDirectory)
    {
        if (path == null) throw new ArgumentNullException(nameof(path));
        if (path == string.Empty) throw new ArgumentException("Value cannot be empty.", nameof(path));

        isDirectory = Directory.Exists(path);

        return isDirectory || File.Exists(path);
    }
}

Questo metodo di supporto è scritto per essere dettagliato e abbastanza conciso da comprendere l'intento la prima volta che lo leggi.

/// <summary>
/// Example usage of <see cref="PathExists(string, out bool)"/>
/// </summary>
public static void Usage()
{
    const string path = @"C:\dev";

    if (!PathHelper.PathExists(path, out var isDirectory))
        return;

    if (isDirectory)
    {
        // Do something with your directory
    }
    else
    {
        // Do something with your file
    }
}

-4

Non funzionerebbe?

var isFile = Regex.IsMatch(path, @"\w{1,}\.\w{1,}$");

1
Questo non funzionerebbe solo perché i nomi delle cartelle possono contenere punti
KSib

Inoltre, i file non devono contenere punti.
Keith Pinson,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.