How to read a text file in project's root directory?

前端 未结 7 813
走了就别回头了
走了就别回头了 2020-12-04 10:45

I want to read the first line of a text file that I added to the root directory of my project. Meaning, my solution explorer is showing the .txt file along side my .cs files

7条回答
  •  感动是毒
    2020-12-04 11:07

    You can have it embedded (build action set to Resource) as well, this is how to retrieve it from there:

    private static UnmanagedMemoryStream GetResourceStream(string resName)
    {
        var assembly = Assembly.GetExecutingAssembly();
        var strResources = assembly.GetName().Name + ".g.resources";
        var rStream = assembly.GetManifestResourceStream(strResources);
        var resourceReader = new ResourceReader(rStream);
        var items = resourceReader.OfType();
        var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
        return (UnmanagedMemoryStream)stream;
    }
    
    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        string resName = "Test.txt";
        var file = GetResourceStream(resName);
        using (var reader = new StreamReader(file))
        {
            var line = reader.ReadLine();
            MessageBox.Show(line);
        }
    }
    

    (Some code taken from this answer by Charles)

提交回复
热议问题