System.IO.FileNotFoundException: 'Could not find file '

Hector A Gonzalez 0 Reputation points
2024-09-04T23:26:06.7966667+00:00

I have the file located in my directory in C:\Users\Cerburus\source\repos\CST-150 ListToGridView\CST-150 ListToGridView\bin\Debug\net8.0-windows\Data\topic6.txt But I keep getting the exception file not found. please I need help

internal class Inventory

{


 

    public List<InvItem> ReadInventoryItems(List<InvItem> invItems) 

    {

        string dirLoc = Application.StartupPath +"Data\\topic6.txt";

        using (var str = File.OpenText(dirLoc))

        {

            foreach (string line in File.ReadLines(dirLoc, Encoding.UTF8)) 

            {

                string[] rowData = line.Split(",");

                invItems.Add(new InvItem(rowData[0].ToString().Trim(),

                    rowData[1].ToString().Trim(), Convert.ToInt32(rowData[2])));

            }

        }

        return invItems;

    }

    public List<InvItem> IncQtyValue(List<InvItem> invItems, int selectedRowIndex)

    {

        //

        int updatedQty = ++invItems[selectedRowIndex].Qty;

        //

        invItems[selectedRowIndex].Qty = updatedQty;

        //

        return invItems;

    }

    /// <summary>

    /// Writes the entire inventory to a file (overwrites existing content)

    /// </summary>

    /// <param name="invItems"></param>

    public void WriteInventory(List<InvItem> invItems)

    {

        string dirloc = Application.StartupPath + "Data\\Topic6.txt";

        try

        {

            using (StreamWriter sw = new StreamWriter(dirloc))

            {

                foreach (var item in invItems)

                {

                    sw.WriteLine($"{item.Type},{item.Color},{item.Qty}");

                }

            }

        }

        catch (Exception ex)

        {

            MessageBox.Show($"An error occurred while writing to the file: {ex.Message}");

        }

    }

    /// <summary>

    /// Appends a new item to the existing inventory file

    /// </summary>

    /// <param name="newItem"></param>

    public void AppendInventory(InvItem newItem)

    {

        string dirloc = Application.StartupPath + "Data\\Topic6.txt";

        try

        {

            using (StreamWriter sw = new StreamWriter(dirloc, true))

            {

                sw.WriteLine($"{newItem.Type},{newItem.Color},{newItem.Qty}");

            }

        }

        catch (Exception ex)

        {

            MessageBox.Show($"An error occurred while appending to the file: {ex.Message}");

        }

    }

}
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,843 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,401 Reputation points
    2024-09-05T21:24:50.1166667+00:00

    Run this code which will find if exists any text files under the executable folder and sub folders.

    var results = Directory.EnumerateFiles(
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory), "*.txt", 
        new EnumerationOptions() { IgnoreInaccessible = true, RecurseSubdirectories = true})
        .ToList();
    

  2. Michael Taylor 53,726 Reputation points
    2024-09-06T19:12:35.6433333+00:00

    Firstly ensure that you DO NOT have that file under that directory in your actual project. It won't work correctly. Create a Data folder in your project and place the file there.

    \SolutionDirectory
       \ProjectDirectory
           \Data
               topic6.txt
           Program.cs
    

    Anything under the bin folder will get wiped out when you rebuild or clean your solution. This is for outputs only.

    Next right click the file in Solution Explorer and set the Build Action to Content. This will cause the file and folder to be copied to the output directory when you build your code. The build system needs to do this, not you.

    Finally note that Application.StartupPath may or may not be where your binary runs from. It is the working directory when the app starts and that doesn't have to be your binary directory. Since you are assuming that it is then you can just use a relative path to find the file.

    using (var str = File.OpenText(@"Data\topic6.txt))
    

    If you absolutely must use a full path AND the working directory may be changed then you need to get the path to the binary file. There are several ways to get this information, here's one.

    string dirLoc = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), @"Data\topic6.txt");
    

    This works for executables that you created but wouldn't work for a web app.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.