无法从“System.IO.FileInfo”转换为字符串
c#
public class program
{
private static void Main()
{
string table = "T_CONSIGNACION";
string directory = @"C:UsersDocumentsExcel"; // Put your test root here.
var dir = new DirectoryInfo(directory);
var file= GetNewestFile(dir);
while (file!=null)
{
if (!File.Exists(file))
{
createLog("directory: " + dir + " nfile: " + fichero + " don't exist");
}
else
{
importFile(file, table);
}
}
}
public static FileInfo GetNewestFile(DirectoryInfo directory)
{
return directory.EnumerateFiles("*.*", SearchOption.AllDirectories)
.MaxBy(f => (f == null ? DateTime.MinValue : f.LastWriteTime));
}
public static void createLog(string logMessage)
{
.......
}
public static string importFile(string file, string table)
{
........
}
}
public static class EnumerableMaxMinExt
{
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
return source.MaxBy(selector, Comparer<TKey>.Default);
}
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource max = sourceIterator.Current;
TKey maxKey = selector(max);
while (sourceIterator.MoveNext())
{
TSource candidate = sourceIterator.Current;
TKey candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, maxKey) > 0)
{
max = candidate;
maxKey = candidateProjected;
}
}
return max;
}
}
}
在“主要”中,我试图获取最后更新的文件(excels 文件);在var file保存文件,然后,在循环:如果文件不存在,创建日志,否则我去进口,但我在得到一个错误,if (!File.Exists(file)) 无法从“System.IO.FileInfo”转换成字符串并出现环路. 我不知道我做得对不对。你能帮助我吗??
回答
File.Exists(...)接受文件名作为参数,而不是FileInfo对象。由于您已经有了FileInfo,您可以使用它来查看文件是否存在。它有一个 property Exists,所以只需使用它:
if (!file.Exists)
或者,如果您真的想使用File.Exists(...),则可以从文件信息中获取文件名。这更冗长,可能效率更低,但我将其作为一个选项提供:
if (!File.Exists(file.FullPath))
至于为什么你的循环永远不会终止,那是因为你永远不会重新分配file变量。您可能需要file= GetNewestFile(dir);在循环内添加,但我感觉您有更多的逻辑错误。我希望函数GetNewestFile总是返回该目录中的相同文件,对吗?如果是这样,它仍然会永远循环。