Ad Code

Responsive Advertisement

Console App Task 12: How to check file name of c:\abc\xyz.txt, c:\abc\pqr.txt, c:\abc\y.txt, c:\abc\eyz.txt is contains y

Console App Task 12: How to check file name of c:\abc\xyz.txt, c:\abc\pqr.txt, c:\abc\y.txt, c:\abc\eyz.txt is contains y 

To check if any of the files in a given list contain the character `'y'` in their file names, you can follow these steps in C#:


1. Extract File Names: Use `Path.GetFileName` to extract just the file names from their paths.
2. Check for Character: Use `IndexOf` to determine if the file names contain the character `'y'`.

Here's a complete example demonstrating how to check a list of file paths to see if their names contain the character `'y'`:

Example Code

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

namespace CheckFileNames
{
    class Program
    {
        static void Main(string[] args)
        {
            // List of file paths
            List<string> filePaths = new List<string>
            {
                @"c:\abc\xyz.txt",
                @"c:\abc\pqr.txt",
                @"c:\abc\y.txt",
                @"c:\abc\eyz.txt"
            };

            // Character to search for
            char searchChar = 'y';

            // Loop through each file path
            foreach (string filePath in filePaths)
            {
                // Extract the file name from the path
                string fileName = Path.GetFileName(filePath);

                // Check if the file name contains the character 'y'
                bool containsChar = fileName.IndexOf(searchChar, StringComparison.OrdinalIgnoreCase) >= 0;

                // Output result
                if (containsChar)
                {
                    Console.WriteLine($"The file name '{fileName}' contains '{searchChar}'.");
                }
                else
                {
                    Console.WriteLine($"The file name '{fileName}' does not contain '{searchChar}'.");
                }
            }
        }
    }
}

Explanation

1. List of File Paths: Define a list of file paths to be checked.

2. Extract File Name: For each file path, use `Path.GetFileName` to get the file name from the full path.

3. Check Character: Use `IndexOf` to check if the file name contains the specified character. The `StringComparison.OrdinalIgnoreCase` parameter makes the search case-insensitive.

4. Output Result: Print whether each file name contains the character `'y'`.

Notes

- Case Sensitivity: By using `StringComparison.OrdinalIgnoreCase`, the check becomes case-insensitive. If you want a case-sensitive check, you can remove this parameter or use `IndexOf(searchChar)`.

- File Existence: This code assumes the files exist. If you want to handle cases where files might not exist, you can use `File.Exists(filePath)` before checking the file name.

If you like comment and share. 🚀

Post a Comment

0 Comments

Ad Code

Responsive Advertisement