C# 获取文件大小

spe*_*258 1 c# file

问题:我想获取文件大小,但文件没有扩展名 example testfile.txt是普通文件,这里是 example(不带引号)“ testfile ”,我也有没有扩展名但名称中有空格的文件 example(没有引号)“我的测试文件”,使用File.Exist读取为文件夹,当前函数我用于文件大小

    using System.IO;
    static long GetFileSize(string FilePath)
    {
        if(File.Exists(FilePath))
        {
            return new FileInfo(FilePath).Length;
        }
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

当前用法:

GetFileSize("C:\\Users\\TestUser\\Appdata\\Local\\Data Manager\\Super User\\User data controller");
Run Code Online (Sandbox Code Playgroud)

它抛出错误:System.IO.IOException: 'The directory name is invalid

文件不违反无效路径字符规则,路径只包含数字、字母和/或空格。

应用程序以管理员身份启动并且 Visual Studio 也以管理员身份启动

完整错误:

    System.IO.IOException
  HResult=0x8007010B
  Message=The directory name is invalid.

  Source=mscorlib
  StackTrace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

   at System.IO.FileSystemEnumerableIterator`1.CommonInit()

   at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)

   at System.IO.Directory.GetFiles(String path, String searchPattern, SearchOption searchOption)

   at test.SuperUserControlEngine.GetFileSize(String FilePath)
   at test.systems.superuser.HoloPart.Control1.ControllerSize()
   at test.systems.superuser.HoloPart.Control1.GetAllControllersSize()
   at test.SuperUserControlEngine.ScanHolos()
   at test.ManagerEngine.Button_Click(Object sender, RoutedEventArgs e)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at test.App.Main()
Run Code Online (Sandbox Code Playgroud)

图片: 测试图片

解决方案:如果有人能告诉我在我的代码中做错了什么并帮助它解决它。

谢谢你。

tgo*_*sch 6

首先检查您对该文件夹的权限。如果您没有文件夹的权限,那么文件操作将不起作用:

using System.IO;
static long GetFileSize(string FilePath)
{
    //if you don't have permission to the folder, Directory.Exists will return False
    if(!Directory.Exists(Path.GetDirectoryName(FilePath))
    {
        //if you land here, it means you don't have permission to the folder
        Debug.Write("Permission denied");
        return -1;
    }
    else if(File.Exists(FilePath))
    {
        return new FileInfo(FilePath).Length;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

阅读更多:在 C# 中读取目录的权限