Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#获取文件大小_C#_File - Fatal编程技术网

C#获取文件大小

C#获取文件大小,c#,file,C#,File,问题:我想获取文件大小,但文件没有扩展名示例testfile.txt是普通文件,下面是示例(不带引号)“testfile”,还有一些文件没有扩展名,但名称中有空格示例(不带引号)“我的测试文件”,使用File.Exist它读取为文件夹,当前函数I用于文件大小 using System.IO; static long GetFileSize(string FilePath) { if(File.Exists(FilePath)) {

问题:我想获取文件大小,但文件没有扩展名示例testfile.txt是普通文件,下面是示例(不带引号)“testfile”,还有一些文件没有扩展名,但名称中有空格示例(不带引号)“我的测试文件”,使用File.Exist它读取为文件夹,当前函数I用于文件大小

    using System.IO;
    static long GetFileSize(string FilePath)
    {
        if(File.Exists(FilePath))
        {
            return new FileInfo(FilePath).Length;
        }
        return 0;
    }
当前使用情况:

GetFileSize("C:\\Users\\TestUser\\Appdata\\Local\\Data Manager\\Super User\\User data controller");
并抛出错误:System.IO.IOException:“目录名无效

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

应用程序以管理员身份启动,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()
图片:

解决方案:如果有人能告诉我代码中的错误并帮助它解决


谢谢。

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

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;
}

阅读更多信息:

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

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;
}


阅读更多信息:

“使用文件。存在它读作文件夹”-解释一下。你的问题不清楚<代码>新文件信息(“C:\Temp\Some file with spaces but not extension”)工作正常。而且当前代码片段甚至不会生成,它有一个语法错误,但我认为这只是一个输入错误。对我来说,它抛出了错误:System.IO.IOException:“目录名无效,C:\Users\TestUser\Appdata\Local\Data Manager\Super User\User Data controller<用户数据控制器不是文件夹。对于哪个路径?@itsme86,我在我的示例“using file.Exist”上面发布了它读作文件夹”-解释一下。你的问题不清楚<代码>新文件信息(“C:\Temp\Some file with spaces but not extension”)工作正常。而且当前代码片段甚至不会生成,它有一个语法错误,但我认为这只是一个输入错误。对我来说,它抛出了一个错误:System.IO.IOException:“目录名无效,C:\Users\TestUser\Appdata\Local\Data Manager\Super User\User Data controller<用户数据控制器是文件而不是文件夹。哪个路径?@itsme86我在我的示例上方发布,插入代码后,它不会抛出任何错误,代码似乎工作正常,调试为空,这意味着它不会输出“权限被拒绝”消息。ACL和权限有时会导致一些令人沮丧和误导的行为。另一个示例:将同一文件复制到c:\user[my login]\appdata\local\文件夹中。代码应该以其原始形式工作(在我的代码更改之前)。问题是权限问题,而不是路径问题,如错误所示。我将此标记为答案,因为问题已解决。祝贺你,伙计。我有这个可能性,因为默认路径是隐藏的,但我仍然可以访问此路径,所以我拒绝了作为可能性。在插入代码后,它不会抛出任何错误,代码似乎工作正常,调试为空,这意味着它不会输出Permission denied message.ACL和permissions有时会导致一些令人沮丧和误导的行为。另一个例子是:将同一文件复制到c:\user[my login]\appdata\local\文件夹中。代码应该以其原始形式工作(在我的代码更改之前)。问题是权限问题,而不是路径问题,如错误所示。我将此标记为答案,因为问题已解决。祝贺你,伙计。我有这个可能性,因为默认路径是隐藏的,但我仍然可以访问这个路径,所以我拒绝了这个可能性