【发布时间】:2013-09-05 22:06:48
【问题描述】:
这是方法:
public void CheckFileType(string directoryPath)
{
var files = Directory.GetFiles(directoryPath).GetEnumerator();
while (files.MoveNext())
{
//get file extension
string fileExtension = Path.GetExtension(Convert.ToString(files.Current));
//get file name without extenstion
string fileName =
Convert.ToString(files.Current).Replace(fileExtension, string.Empty);
//Check for JPG File Format
if (fileExtension == ".jpg" || fileExtension == ".JPG")
// or // ImageFormat.Jpeg.ToString()
{
try
{
//OCR Operations ...
MODI.Document md = new MODI.Document();
md.Create(Convert.ToString(files.Current));
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
MODI.Image image = (MODI.Image)md.Images[0];
//create text file with the same Image file name
FileStream createFile =
new FileStream(fileName + ".txt", FileMode.CreateNew);
//save the image text in the text file
StreamWriter writeFile = new StreamWriter(createFile);
writeFile.Write(image.Layout.Text);
writeFile.Close();
}
catch (Exception exc)
{
//uncomment the below code to see the expected errors
w.Write(exc.ToString() + Environment.NewLine);
}
}
}
w.Close();
}
当变量 files.Current 包含文件名:RadarGifAnimatoion 并且文件类型为:File 我在文件上做了属性,在类型下我只看到:文件 这个文件大小是 32 字节,我猜这个文件是坏的或空的。
然后我得到异常就行了:
string fileName = Convert.ToString(files.Current).Replace(fileExtension, string.Empty);
字符串长度不能为零
System.ArgumentException 未处理 HResult=-2147024809
Message=String 的长度不能为零。参数名称:oldValue
源=mscorlib 参数名=oldValue
【问题讨论】:
-
你看过堆栈跟踪吗?
-
Replace(fileExtension, string.Empty)将在fileExtension为空字符串时抛出此错误 - 即当文件没有扩展名时(“文件类型只是文件”) -
您可以使用它来修复您的代码:msdn.microsoft.com/en-us/library/…
-
@Blorgbeard 这当然是一种选择,但this one 似乎更直接。我喜欢方法名称与 OP 代码中的注释的匹配程度。
-
@hvd 看看他在用无扩展路径做什么 - 他正在重新实现 ChangeExtension :P