none
Pick files (pdf, .docx) from file folder RRS feed

  • Question

  • I am using a class library writing c# code. 

    My requirement is I need to pick only the files with the file name I mention that contains 'p. If anything other than that should not be picked.

    How can I write this. Please advise


    RH

    Monday, August 19, 2019 9:23 PM

All replies

  • Hi Dan2890, 

    Thank you for posting here.

    For your question, you want to pick files from file folder with the file name contains 'p’.

    I make a sample on my side, and I search all the file names contains ‘p’ and show the names.

    Here’s my code.

            static void Main(string[] args)
            {
                string path = @"D:\TestFile";
                if (File.Exists(path))
                {
                    Console.WriteLine($"Processed file '{path}'.");
                }
                else if (Directory.Exists(path))
                {
                    string[] fileEntries = Directory.GetFiles(path);
                    for (int i = 0; i < fileEntries.Length; i++)
                    {
                        string s = Path.GetFileNameWithoutExtension(fileEntries[i]);
                        if (s.Contains("p"))
                        {
                            Console.WriteLine(s);
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"{path} is not a valid file or directory.");
                }
                Console.ReadKey();
            }

    Files in my ‘TestFile’:

    Result of the test:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, August 20, 2019 8:49 AM
    Moderator
  • thank you, Xingyu.

    I am looking for c# class library not a console application. 

    Actually my other application will reference this above code dll and call this c# library passing the Unique value associated with the .docx file name.

    Can we make this filename dynamic coming from other application ?

    I will be passing the Unique filename parameter from other application to call this class.

    Please advise how to achieve this, thank you in advance

    Can we make this filename dynamic coming from other application ?


    RH


    • Edited by Dan2890 Tuesday, August 20, 2019 11:57 AM a
    Tuesday, August 20, 2019 11:57 AM
  • Code stay almost the same. No console interaction here. So return values not necesarily contain filenames:

    using System;
    using System.Collections.Generic;
    using System.IO;
    
    namespace MSDN.Forums.Example
    {
        public class FileSelect
        {
            public IEnumerable<String> PickFile(String FileName, String Contains)
            {
                if (File.Exists(FileName))
                {
                    yield return FileName;
                }
                else if (Directory.Exists(FileName))
                {
                    var fileEntries = Directory.GetFiles(FileName);
                    foreach (var file in fileEntries)
                    {
                        var s = Path.GetFileNameWithoutExtension(file);
                        if (s.Contains(Contains))
                        {
                            yield return s;
                        }
                    }
                }
                else
                {
                    yield return $"{FileName} is not a valid file or directory.";
                }
            }
        }
    }
    

    Tuesday, August 20, 2019 12:29 PM
  • This may be a possible direction to take.

    EDIT Can be done in a class project, add a reference to Windows Forms for working with the OpenDialog component.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Windows.Forms;
    using static System.IO.Path;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            private List<string> _fileNames;
            public Form1()
            {
                InitializeComponent();
                openFileDialog1.FileOk += OpenFileDialog1_FileOk;
               
            }
            private void OpenFileDialog1_FileOk(object sender, CancelEventArgs e)
            {
                _fileNames = openFileDialog1
                    .FileNames
                    .Where(file => GetFileName(file)
                        .ToLower().Contains("g"))
                    .ToList();
     }
    
            private void SelectButton_Click(object sender, EventArgs e)
            {
                _fileNames = new List<string>();
                if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
                listBox1.DataSource = _fileNames.Count > 0 ? _fileNames : null;
            }
        }
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange



    Tuesday, August 20, 2019 1:41 PM
    Moderator
  • Hi Chris, thanks for the reply.

    In the code you provided, there is no directory or folder location where the Filename needs to be looked into.

    The directory location will be passed as a paramter from other application calling this Class Library.

    Please advise how can I enhance this.


    RH

    Wednesday, August 21, 2019 11:55 AM
  • Dan,

    the code works well when a directory/folder is provided as parameter 'FileName'. Let me make this simple change:

    using System;
    using System.Collections.Generic;
    using System.IO;
    
    namespace MSDN.Forums.Example
    {
        public static class FileSelect
        {
            public static IEnumerable<String> PickFile(String FileSystemEntryName, String Contains)
            {
                if (File.Exists(FileSystemEntryName))
                {
                    yield return FileSystemEntryName;
                }
                else if (Directory.Exists(FileSystemEntryName))
                {
                    var fileEntries = Directory.GetFiles(FileSystemEntryName);
                    foreach (var file in fileEntries)
                    {
                        var s = Path.GetFileNameWithoutExtension(file);
                        if (s.Contains(Contains))
                        {
                            yield return s;
                        }
                    }
                }
                else
                {
                    yield return $"{FileSystemEntryName} is not a valid file or directory.";
                }
            }
        }
    }
    
    You can call FileSelect.PickFile(...) with a FileName (full path) or directory name

    Thursday, August 22, 2019 5:32 AM
  • thanks Chris.

    A quick question, lets say I am passing the Directory parameter where the files should be picked from, GUID)

    Note : FileName will be GUID + FileName (with extension like .pdf, .docx) 

    so when I call FileSelect.PickFile method from other application.....will it pick all the related files by passing Directory and GUID parameters ?

    Will this be hold on another variable ? say like

    string varOut = FileSelect.PickFile(Directory, GUID)  ??


    RH

    Thursday, August 22, 2019 11:37 AM
  • Dan,

    not sure if I understood your intend. Say, you got a directory C:\MyAppDir\Files\ with all kind of files in it. say
    File.txt
    MyApp.exe
    SomeDocument.pdf
    000-000-111-222.docx (suppose the filename is a guid)
    000-000-111-222.xlsx
    000-000-111-222.pdf
    333-000-111-222.xlsx

    When you call

    var files = FileSelect.PickFile("C:\MyAppDir\Files\", "000-000-111-222");

    the files variable will get a list with three elements (000-000-111-222.docx/.xslx/.pdf)

    Or do you want to get all files with a filename that look like a guid? I that case you would need to change FilePic(string, string) to FilePick(string, regex) and do a different implementation.

    One more thing: FilePick() does not return a string. It returns a IEnumerable<string>. That's quite a difference.

    Thursday, August 22, 2019 11:55 AM
  • The latter part is correct, I want to get all files with a filename that look like a guid. In the above case say my GUID is 000-000 then my method should be picking all 3 files like 

    000-000-111-222.docx 
    000-000-111-222.xlsx
    000-000-111-222.pdf

    For this is there any enhancement I can for this code ?


    RH

    Thursday, August 22, 2019 12:05 PM
  • in that case you have to check if the file name matches a guid:

            public static IEnumerable<String> PickGuidFile(String path)
            {
                if (File.Exists(path))
                {
                    yield return path;
                }
                else if (Directory.Exists(path))
                {
                    var fileEntries = Directory.GetFiles(path);
                    var rx = new Regex(@"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$");
                    foreach (var file in fileEntries)
                    {
                        var s = Path.GetFileNameWithoutExtension(file);
                        if (rx.IsMatch(s))
                        {
                            yield return s;
                        }
                    }
                }
                else
                {
                    yield return $"{path} is not a valid directory.";
                }
            }
    Since I'm no wizard of RegEx I used a regex expression as found here.

    Friday, August 23, 2019 6:11 AM