简体   繁体   中英

How to add multiple files using Directory.GetFiles() in C#?

This question might have been asked before, however I am not able to pass three parameters in single loop which I need for my method. I have like thousands of files in that directory (xml,jpg,tiff) (mixed).

This is something what I'm trying to get.

protected void btn_Click(object sender, EventArgs e)
        {
            var path = @"d:\xmlfiles";
            foreach (var file in Directory.GetFiles(path))
            {
                ProcessFile(file,param2,param3);
            }

        }

    static void ProcessFile(string file_xml, string file_jpg, string file_tiff)
        {
            // do processing here...
            //Adding data to sql
        }

I tried Path.GetExtension , but it only gives extension. I have to pass file name and the logic is in the method Processfile() .

I saw many questions asked before which only returns single file. Any other way for a workaround?

Any helpe would be appreciated. Thanks.

So you have a directory containing files like this:

  • Foo.xml , Foo.jpg , Foo.tiff
  • Bar.xml , Bar.jpg , Bar.tiff
  • Baz.xml , Baz.jpg , Baz.tiff

And you want to process equally named files together. Then why not pick and enumerate one extension, and reconstruct the accompanying file names:

foreach (var xmlFile in Directory.GetFiles(path, "*.xml"))
{
    var extensionLess = Path.GetFilenameWithoutExtension(xmlFile);

    var jpgFile = Path.Combine(path, extensionLess + ".jpg");
    var tiffFile = Path.Combine(path, extensionLess + ".tiff");

    ProcessFile(xmlFile, jpgFile, tiffFile);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM