Преобразование из python в exe, возможно, не включало в себя все зависимости, поэтому в новой системе не было обнаружено ни единого пакета. Может быть, попробовать другой метод преобразования? Или посмотрите, не используется ли тот, который вы использовали, зависимости?
From Как узнать, путь к файлу или каталогу :
// 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");
Согласно комментариям ниже, если вы используете .NET 4.0 или новее (и максимальная производительность не критична), вы можете написать код более чистым способом:
// 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");
Очень поздно стороне здесь, но я нашел Nullable<Boolean>
возвращаемое значение быть довольно уродливым - IsDirectory(string path)
, возврат null
не приравнивается к несуществующему пути без подробного комментария, таким образом, я придумал следующее:
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);
}
}
Этот вспомогательный метод записан, чтобы быть подробным и достаточно кратким для понимания намерения в первый раз, когда Вы читаете его.
/// <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
}
}
Наиболее точным подходом будет использование некоторого кода взаимодействия из 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);
Вы бы тогда назвали его так:
#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);
}
В качестве альтернативы Directory.Exists () вы можете использовать метод File.GetAttributes () для получения атрибутов файла или каталога, чтобы вы могли создать вспомогательный метод, подобный этому :
private static bool IsDirectory(string path)
{
System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
return (fa & FileAttributes.Directory) != 0;
}
Вы также можете рассмотреть возможность добавления объекта в свойство тега элемента управления TreeView при заполнении элемента управления, который содержит дополнительные метаданные для элемента. Например, вы можете добавить объект FileInfo для файлов и объект DirectoryInfo для каталогов, а затем проверить тип элемента в свойстве тега, чтобы сохранить дополнительные системные вызовы для получения этих данных при нажатии на элемент.
Как насчет их использования?
File.Exists();
Directory.Exists();