0

I am creating new files at run time inside App_Data folder. My requirement is to read these file names and proceed further. My code is as below :

var filenames = from fullFilename
                 in Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory + 
                                             "\\App_Data\\", "*.xml")
                select Path.GetFileName(fullFilename);

foreach (string filename in filenames)
{
    System.Diagnostics.Debug.WriteLine("filename -- "+filename);
}

Above code says

cannot find the directory App_Data.

But this exists in my project.

How can I get names of all the files using this enumerator?

UPDATE : While creating file at run time, I use HostingEnvironment.MapPath(@"/myproject/") +"/App_Data". This creates file in the location. But it doesnot allows me to read from there.

Neha
  • 143
  • 4
  • 19
  • Just because it is present in your source tree doesn't mean it is present in your applications binary folder where your executable is compiled to. – Uwe Keim Jan 13 '17 at 06:53
  • 2
    Is the value of `AppDomain.CurrentDomain.BaseDirectory` exactly what you think it is? – grek40 Jan 13 '17 at 06:54
  • I think instead of `AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\"` you want `Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)` – Mohit S Jan 13 '17 at 06:56
  • Where is `App_Data` located? is that a folder inside your solution or it is the system folder`AppData` – sujith karivelil Jan 13 '17 at 06:59
  • @MohitShrivastava I tried this but it still gives error as "Exception thrown: 'System.IO.DirectoryNotFoundException' in mscorlib.dll ". This is obvious because this gives path as "C:\Users\User1\AppData\Roaming" which is not correct. This App_Data is inside my project. – Neha Jan 13 '17 at 07:03
  • @un-lucky It is inside the project. Path is " MyProject/App_Data " – Neha Jan 13 '17 at 07:04
  • @grek40 Yes this gives the correct path but I don't understand why it cannot find it. – Neha Jan 13 '17 at 07:05
  • Refer http://stackoverflow.com/questions/8669833/why-appdomain-currentdomain-basedirectory-not-contains-bin-in-asp-net-app, this may help – Mukul Varshney Jan 13 '17 at 07:21
  • I posted an answer below, but now I don't think it's relevant, and I think I understand why everyone was questioning the existence of an 'App_Data' path in the app domain. I think my answer is only relevant in a web app. – nocturns2 Jan 13 '17 at 08:04

2 Answers2

0

If you add a using System.IO or a reference to it, this should find all the .xml files in the App_Data folder, in your application environment:

        DirectoryInfo di = new DirectoryInfo(Server.MapPath("/App_Data"));
        var fi = di.EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly);

// fi should contain the enumeration of files found at that path
// you can iterate over fi and have all the file info of each file found

[UPDATE]

If you already have the path string resolved, you can replace the entire Server.MapPath("/App_Data") with your path for a desktop app, and the rest stays the same.

To iterate over the collection just use a foreach loop as in:

            foreach (FileInfo file in fi)
            {
                string s = "File Name: " + file.Name + "\r";
                s += "Full Path: " + file.FullName + "\r";
                s += "File Ext.: " + file.Extension + "\r";
                MessageBox.Show(s);
            }

[ UPDATE 2 ]

Since the OP is referring to a web scenario

By adding the using System.Web.Hosting statement to my controller I was able to test the 'HostingEnvironment.MapPath', in an mvc sample app. Here's what I came up with.

This example locates the virtual path '/App_Data', gathers the '.xml' files it finds in the path. Then it iterates over the collection and reads each file's contents into an array element. Finally, it displays the file names as links in the view, as well as each file's content with a heading#. Keep in mind that this may not be the most optimized code sample.

C# Code: in mvc Controller

        DirectoryInfo di = new DirectoryInfo(HostingEnvironment.MapPath("/App_Data"));
        var fi = di.EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly);
        ViewBag.Files = fi;
        string[] fs = new string[fi.Count()];
        int fc = fi.Count();
        int x = 0;
        foreach (FileInfo f in fi)
        {
            StreamReader sr = new StreamReader(f.FullName);
            fs[x] = sr.ReadToEnd();
            sr.Close();
            if (x < fc) x++;
        }
        ViewBag.Contents = fs;
        ViewBag.ContCount = fc;

Html: in View

<div>
    <h3>Files Found:</h3>
    <p>
        @foreach (FileInfo f in @ViewBag.Files)
        {
            <a href="@f.FullName">@f.Name</a><br />
        }

    </p>

</div>
<div>
    <h3>File Contents:</h3>
    @for (int c = 0; c < @ViewBag.ContCount; c++)
    {
        <h4>Heading @(c)</h4>
        <p>
            @ViewBag.Contents[@c]
        </p>
        <hr />
    }
</div>
nocturns2
  • 663
  • 10
  • 17
0

Actually the AppDomain.CurrentDomain.BaseDirectory gives you the current working directory, While debugging it gives you the path Your Projectfolder\\bin\\Debug\\. And you wanted to Find the App_Data folder inside the Project folder, not in debug So you have to come back to the Project folder and then find the App_Data like the following:

string projectFolder = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.FullName;
string folderAppData = Path.Combine(projectFolder, "App_Data");
if (Directory.Exists(folderAppData))
{
    foreach (string file in Directory.EnumerateFiles(folderAppData,"*.xml"))
    {
           // Do your stuff here
    }
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • Thanks. But issue is in iterating files inside that folder. I am able to find the path with HostingEnvironment.MapPath(@"/myproject/") +"/App_Data", as I am already creating files inside that folder as the first step. While reading files, it throws exception "Cannot find part of the path C:\Users\User1\Workspace\Myproject\App_Data" – Neha Jan 13 '17 at 07:40
  • If it is web application, the use `Server.MapPath` – sujith karivelil Jan 13 '17 at 07:43