我正在尝试一个非常基本的脚本来拉取目录中所有火灾的大小。作为语言的新手,我知道逻辑但不了解.NET框架。我目前正在使用.NET Framework 4.5.1来构建它。
问题:
这些工具可以很好地满足我的机器和实验室中其他机器的所有期望,但是当我尝试在其他机器上运行脚本时,我收到以下错误消息:
CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Diagnostics;
using System.Threading;
using System.Security.Cryptography;
using System.Numerics;
using System.Text.RegularExpressions;
namespace FolderSize
{
class Program
{
public int foldersize = 0;
public static float foldersizeInMB = float.Parse("0.0");
public static BigInteger SizeInBytes = new BigInteger();
static void Main(string[] args)
{
string directoryName = "";
SizeInBytes = BigInteger.Parse("0");
if (args.GetLength(0)<1)
{
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("No path provided. Please run the command again with correct arguments");
Console.WriteLine("Syntax: ");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("FolderSize ");
Console.Write("Path_of_the_folder(InQuotes)");
Console.ForegroundColor = ConsoleColor.White;
}
else
{
directoryName = args[0];
if ( !directoryName.EndsWith(@"\"))
{
directoryName += @"\";
}
DirectoryInfo dir = new DirectoryInfo(directoryName);
if (dir.Exists)
{
getdirNames(dir);
Console.Write((SizeInBytes / (1024 * 1024)).ToString());
}
else
{
Console.Write("Directory Not Found");
}
}
}
private static void getdirNames(DirectoryInfo dir)
{
try
{
foreach (DirectoryInfo d in dir.GetDirectories())
{
foldersizeInMB = float.Parse("0.0");
try
{
foreach (FileInfo f in d.GetFiles())
{
SizeInBytes += f.Length;
string text = f.FullName;
int level = text.Split('\\').Length - 1;
foldersizeInMB += ((float)f.Length/1024);
Console.WriteLine("File?" + level.ToString() + "?" + f.FullName + "?" + ((float)f.Length/1024));
}
Console.WriteLine("Folder?" + (d.FullName.Split('\\').Length-1) + "?" + d.FullName + "?" + foldersizeInMB);
getdirNames(d);
}
catch (Exception)
{
}
}
}
catch
{
}
}
}
}
答案 0 :(得分:2)
问题在于解析浮点数我猜。你可能有另一个系统有另一个小数分隔符,很可能因为它设置为另一种语言。
这是失败的一行:
public static float foldersizeInMB = float.Parse("0.0");
应该是:
public static float foldersizeInMB = 0.0f;
或者,如果您出于某种原因需要解析它,请使用支持您的格式的文化:
public static float foldersizeInMB = float.Parse("0.0", CultureInfo.InvariantCulture);