Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

c# - Argument 1: cannot convert from System.IO.FileInfo to 'string'

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace FunkcjaSpilit
{

    class Program2
    {

        static int _MinWordLength = 7;
        static void Main()
        {
            DirectoryInfo filePaths = new DirectoryInfo(@"D:project_IAD");
            FileInfo[] Files = filePaths.GetFiles("*.sgm");
            List<string> firstone = new List<string>();



            foreach (FileInfo file in Files)
            {
                int longWordsCount = CalculateLongWordsCount(file, _MinWordLength);

                Console.WriteLine("W tekscie numer: " + firstone.IndexOf(file) + " liczba d?ugich s?ów to " + longWordsCount);
            }
            Console.ReadLine();
        }

        private static int CalculateLongWordsCount(FileInfo file, int minWordLength)
        {
            return file.Split(' ').Where(wordInText => wordInText.Length >= minWordLength).Count();
        }

    }
}

After runing this code an error occurs: (local variable) FileInfo file CS 1503: Argument 1: cannot convert from System.IO.FileInfo to 'string' How it can be fixed?

question from:https://stackoverflow.com/questions/65602296/argument-1-cannot-convert-from-system-io-fileinfo-to-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I see two problems in the code. Both of them come from not understanding what the FileInfo struct is for. I'll fix one of the errors, and leave you to learn from my fix to do the second yourself.

private static int CalculateLongWordsCount(FileInfo file, int minWordLength)
{
    return File.ReadLines(file.FullName).
        Select(line => line.Split(' ').Count(word => word.Length > minWordLength)).
        Sum();
}

You could also use File.ReadAllText() for this and it would be simpler and more closely resemble the original code, but I prefer ReadLines() for giving at least some protection against large files blowing up your memory.

The other problem is in this expression:

firstone.IndexOf(file)

But, again, I leave this to you to fix, so that you will be sure to understand how to use the FileInfo struct. Separate from the FileInfo problem, this expression will also always return -1, because no data is ever added to the firstone list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...