C#如何判断远程驱动器是否有足够的空间写入文件?如何确定远程驱动器是否有足够的空间让我在.Net中使用C#上传给定文件?有两种可能的解决方案。调用Win32函数GetDiskFreeSpaceEx。这是一个示例程序:internalstaticclassWin32{[DllImport("kernel32.dll",CharSet=CharSet.Auto,SetLastError=true)]internalstaticexternboolGetDiskFreeSpaceEx(stringdrive,outlongfreeBytesForUser,outlongtotalBytes,outlong免费字节);}classProgram{staticvoidMain(string[]args){longfreeBytesForUser;长总字节数;长空闲字节;如果(Win32.GetDiskFreeSpaceEx(@"\primecargohold",outfreeBytesForUser,outtotalBytes,outfreeBytes)){Cons.WriteLine(freeBytesForUser);Console.WriteLine(totalBytes);Console.WriteLine(freeBytes);}}}使用系统管理界面。这篇文章中还有另一个答案对此进行了描述。这种方法实际上是为了与PowerShell等脚本语言一起工作而设计的。它只是为了让对象正确而做很多事情。最后,我怀疑,这个方法归结为调用GetDiskFreeSpaceEx。任何使用C#进行任何认真的Windows开发的人都可能最终调用大量Win32函数。.NET框架并未涵盖100%的Win32API。任何大型程序都可以快速发现只能通过Win32API获得的.NET库中的漏洞。我会得到.NET的Win32包装器并将其包含在您的项目中。这将使您能够即时访问几乎所有Win32API。使用System.Management使用WMI;//获取所有网络驱动器(drivetype=4)SelectQueryquery=newSelectQuery("selectName,VolumeName,FreeSpacefromwin32_logicaldiskwheredrivetype=4");ManagementObjectSearcher搜索器=newManagementObjectSearcher(query);foreach(ManagementObjectdriveinsearcher.Get()){stringName=(string)drive["Name"];字符串VolumeName=(string)drive["VolumeName"];UInt64freeSpace=(UInt64)drive["FreeSpace"];基于(被盗)http://www.dreamincode.net/code/snippet1576.htm你是在谈论将网络共享映射到计算机上的逻辑驱动器吗?如果是这样,您可以使用DriveInfo。DriveInfoinfo=newDriveInfo("X:");info.AvailableFreeSpace;DriveInfo仅适用于逻辑驱动器,因此如果您仅使用完整共享(UNC)名称,我认为上述代码将无法运行。我不确定GetDiskFreeSpaceEx是否适用于UNC共享,但如果它确实使用它,否则这里是如何将UNC共享安装到逻辑驱动器:编辑GetDiskFreeSpaceEx确实适用于UNC共享,使用它......但是,这段代码只是需要删除太多工作,如果您想在代码中将UNC共享挂载为本地驱动器,则非常方便。以上是C#学习教程:C#如何判断远程驱动器是否有足够空间写入文件?如果分享的内容对你有用,需要进一步了解C#学习教程,希望你多多关注——公共intdwType;公共intdwDisplayType;公共intdwUsage;[MarshalAs(UnmanagedType.LPStr)]publicstringlpLocalName;[MarshalAs(UnmanagedType.LPStr)]publicstringlpRemoteName;[MarshalAs(UnmanagedType.LPStr)]publicstringlpComment;)]公共字符串lpProvider;publicoverrideStringToString(){Stringstr="LocalName:"+lpLocalName+"RemoteName:"+lpRemoteName+"Comment:"+lpComment+"lpProvider:"+lpProvider;返回(str);}}[DllImport("mpr.dll")]publicstaticexternintWNetAddConnection2A([MarshalAs(UnmanagedType.LPArray)]NETRESOURCEA[]lpNetResource,[MarshalAs(UnmanagedType.LPStr)]字符串lpPassword,[MarshalAs(UnmanagedType.LPStr)]字符串用户名,intdwFlags);[DllImport("mpr.dll",CharSet=System.Runtime.InteropServices.CharSet.Auto)]privatestaticexternintWNetCancelConnection2A([MarshalAs(UnmanagedType.LPStr)]stringlpName,intdwFlags,intfForce);publicintGetDriveSpace(stringshareName,stringuserName,字符串密码){NETRESOURCEA[]n=newNETRESOURCEA[1];n[0]=newNETRESOURCEA();n[0].dwScope=0;n[0].dwType=0;n[0].dwDisplayType=0;n[0].dwUsage=0;n[0].dwType=1;n[0].lpLocalName="x:";n[0].lpRemoteName=shareName;n[0].lpProvider=null;intres=WNetAddConnection2A(n,userName,password,1);DriveInfoinfo=newDriveInfo("x:");intspace=info.AvailableFreeSpace;interr=0;err=WNetCancelConnection2A("x:",0,1);返回空间;}}本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除,如需转载请注明出处:
