225

Instead of running an external program with its path hardcoded, I would like to get the current Project Dir. I'm calling an external program using a process in the custom task.

How would I do that? AppDomain.CurrentDomain.BaseDirectory just gives me the location of VS 2008.

sean
  • 11,164
  • 8
  • 48
  • 56
  • Hey sean, it seems to me that mentioning MSBuild in the title of the question is a bit of a red herring. The question seems to be (and all answers understand it to be) how to programmatically obtain the project directory, that is, the directory of the source code. I would like to edit the question to reflect this, but I wanted to check with you first. – Mike Nakis Oct 28 '22 at 11:16
  • Hi Mike. Mentioning the ProjectDir should have sufficed. But luckily I did mention "custom build task" as I have managed to find this project and it looks like the task needed to get at the /Scripts folder to compress js files. Strangely, the path is still being hardcoded. – sean Oct 29 '22 at 20:01
  • In this case I think that the "custom build task" and even "MSBuild" could be mentioned in a "For context, here is what I am trying to do:" footnote at the end of the question. But as it stands it is unclear to me what you want, so I will not intervene. – Mike Nakis Oct 30 '22 at 09:45

28 Answers28

429
using System;
using System.IO;

// This will get the current WORKING directory (i.e. \bin\Debug)
string workingDirectory = Environment.CurrentDirectory;
// or: Directory.GetCurrentDirectory() gives the same result

// This will get the current PROJECT bin directory (ie ../bin/)
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;

// This will get the current PROJECT directory
string projectDirectory = Directory.GetParent(workingDirectory).Parent.Parent.FullName;
Vimal CK
  • 3,543
  • 1
  • 26
  • 47
mohammed sameeh
  • 4,711
  • 3
  • 18
  • 19
  • 39
    +1 for the Directory.GetParent() so we dont get the \bin\Debug directory :) – Eystein Bye Dec 04 '12 at 12:10
  • 11
    What if we use a custom target CPU? For instance, if I set my build to target x64 it creates another folder in between those. – Samir Aguiar Jul 28 '16 at 19:35
  • 9
    This is the correct answer. The accepted answer returns the path to the bin directory, which is NOT the project directory. – pookie Jul 19 '17 at 22:38
  • 1
    @pookie's answer is recursively wrong for my case. This is giving me */{project}/bin folder, so I need to concat a .parent. – Captain Prinny Aug 01 '19 at 13:48
  • Thank you! Everywhere I have looked, answers point to the bin\debug directory. I want exactly this – Bijan Negari Feb 22 '22 at 08:48
  • 5
    This answer is wrong because it makes assumptions about the project configuration, so it may work for some projects but not for other projects. Furthermore, all those who comment saying "this is the correct answer" are wrong; the best they can say is "it worked for me", and it only worked for them because the moon was in the right phase and the planets were aligned. What is even worse is that if you make changes to your project configuration, this answer will stop working for you, and you will have no warning or indication why. – Mike Nakis Jun 21 '22 at 10:09
  • 3
    To get Project file path we should use Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName – FreePhoenix888 Feb 21 '23 at 08:23
  • 1
    @FreePhoenix888 Your comment is the ACTUAL answer. Thanks! The accepted and upvoted literally give me "C:\Program Files\IIS Express". Of course the question title is bad. "current project directory", "project directory" is where you find your *.sln, *.proj, *.cs files, "working/app directory" is where you find your *.exe, *.dll files. And what's up with the "current"? (the last bit is directed @sean) – Bitterblue Mar 20 '23 at 11:50
150

You can try one of this two methods.

string startupPath = System.IO.Directory.GetCurrentDirectory();

string startupPath = Environment.CurrentDirectory;

Tell me, which one seems to you better

Iralda Mitro
  • 7,190
  • 5
  • 24
  • 29
  • 113
    These two above points you to the bin directory, so if you have for example one bin directory for your whole solution it will point you there and NOT to your project directory (or two levels BELOW your project directory) – matcheek Mar 26 '12 at 16:38
  • 21
    Both solutions will not work as expected when using Test Explorer. – Gucu112 Sep 19 '18 at 08:51
  • 2
    I wish to add that this is in fact the current answer. I went the the other answer, but that kept putting my files two levels above the current working directory in .NET 5.0. I had to circle back to this answer to place files in my current project directory. So, this is indeed the right answer, at least, in my console .NET 5 app. – Jay Aug 20 '21 at 09:17
  • Both gave me this location: c:\windows\system32\inetsrv – Khalid Bin Sarower Jul 14 '22 at 06:55
90

If a project is running on an IIS express, the Environment.CurrentDirectory could point to where IIS Express is located ( the default path would be C:\Program Files (x86)\IIS Express ), not to where your project resides.


This is probably the most suitable directory path for various kinds of projects.

AppDomain.CurrentDomain.BaseDirectory

This is the MSDN definition.

Gets the base directory that the assembly resolver uses to probe for assemblies.

hina10531
  • 3,938
  • 4
  • 40
  • 59
  • 40
    9 years later and someone actually has the real answer. – Jeff Davis Aug 05 '18 at 21:04
  • There is no AppDomain in .NET Core. You would have to do something like this. System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += context => InvokeBatchProcessors(); – Latency Nov 29 '18 at 16:37
  • Besides that, you can use the Visual Studio SDK and get the location from the solution configuration layout using DTE2. – Latency Nov 29 '18 at 16:41
  • 2
    @Latency there is in a .net core 3 WPF project – Alexander Jul 31 '19 at 20:46
  • Yeah, I read the specs. Nothing like 3,0 that's for sure. I have been using it since. Very pleased. I think I posted this pre 3.0 so thanks for the clarification. – Latency Aug 04 '19 at 05:12
  • Only one that seems to work when its ran as a scheduled task. – RustyH May 21 '20 at 20:21
  • u are king of kings – pata Jun 13 '20 at 22:53
  • This doesn't work on debug because it drops /bin/debug to path. – Anubix Aug 10 '22 at 06:58
  • 1
    This answer does not give the project directory. The project directory is where your project file is located. This answer gives the directory of the binaries of your project, which is most definitely ***not*** the directory where your project file is located. – Mike Nakis Sep 02 '22 at 10:27
50

The proper1 way to get the root folder of a C# project is to leverage the [CallerFilePath] attribute to obtain the full path name of a source file, and then subtract the filename plus extension from it, leaving you with the path to the project.

Here is how to actually do it:

In the root folder of your project, add file ProjectSourcePath.cs with the following content:

internal static class ProjectSourcePath
{
    private const  string  myRelativePath = nameof(ProjectSourcePath) + ".cs";
    private static string? lazyValue;
    public  static string  Value => lazyValue ??= calculatePath();

    private static string calculatePath()
    {
        string pathName = GetSourceFilePathName();
        Assert( pathName.EndsWith( myRelativePath, StringComparison.Ordinal ) );
        return pathName.Substring( 0, pathName.Length - myRelativePath.Length );
    }
}

The string? requires a pretty late version of C# with #nullable enable; if you don't have it, then just remove the ?.

The Assert() function is my own; you can replace it with your own, or omit it, if you like living your life dangerously.

The function GetSourceFilePathName() is defined as follows:

using System.Runtime.CompilerServices

    public static string GetSourceFilePathName( [CallerFilePath] string? callerFilePath = null ) //
        => callerFilePath ?? "";

Once you have the above, you can use it as follows:

string projectSourcePath = ProjectSourcePath.Value;

1 'proper' as in: fool-proof; sure-fire; without presumptions; not being held together by shoestrings; not bound to work for some projects but fail for others; not likely to horribly break without a warning when you change unrelated things; etc.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • 2
    This is nice. Well done and thanks – Alan Macdonald May 24 '22 at 12:39
  • 1
    You could use `Directory.GetParent(pathName).FullName` or `FullPath` instead of `Substring`. More readable, although it doesn't have it won't have the directory separators / or \ at the end. – NotAPro Jun 30 '22 at 01:45
  • 4
    @NotAPro sure I could, but what would I gain by doing that? If you look at the source code of `Directory.GetParent()` it does a whole lot of weird stuff, including path normalization, (which is unnecessary since `CallerFilePath` already yields a normalized path,) and at the end of all that weird stuff it does an inefficient reverse linear search for the index of the last separator char, (which I already know with `pathName.Length - myRelativePath.Length`,) and finally an invocation of nothing other than... `Substring()`. So, why do all that instead of just `Substring()`? – Mike Nakis Jun 30 '22 at 08:18
  • You say "more readable" -- meh, that's debatable. Even if I was to agree that `GetParent()` is more readable, it would only be marginally more readable. At the same time when you see `GetParent()` you know it is a complicated function, so you have to wonder what weird things could happen in there, while with `Substring()` it is very clear what happens. – Mike Nakis Jun 30 '22 at 08:24
  • 2
    @MikeNakis well without knowing all of that, I think `GetParent` looks nicer, because you don't have to figure out substring arithmetic; but you having said all of that, `Substring` makes more sense. – NotAPro Jun 30 '22 at 15:31
  • 3
    This is very old, I know, but I think it bears mentioning that this only works if you've compiled the project on the same machine as the one executing it. Maybe that's implicit in the original question, I can't tell. Regardless, for future googlers, be aware that this will inline the actual absolute path to the file on the machine during compilation, so it is NOT portable. – Thomas Aug 23 '22 at 00:31
  • 1
    @Thomas yes, that's true, but the OP asked for the "project directory", that's only defined for source code, and he wants it in the context of MSBuild, which implies during compilation time, which further guarantees that the source code better be available. – Mike Nakis Aug 23 '22 at 01:08
  • @MikeNakis Yeah I figured it was something like that. I'm not super familiar with the csharp/dotnet ecosystem. Nevertheless, I think it bears mentioning in case future googlers like myself misinterpret the question at hand and see this as an all-purpose solution. Nothing wrong with this answer, though. – Thomas Aug 23 '22 at 22:42
  • 1
    This is the only solution that works for identifying files while debugging a visual studio instance with another visual studio instance – Simone Mar 03 '23 at 15:25
27

This will also give you the project directory by navigating two levels up from the current executing directory (this won't return the project directory for every build, but this is the most common).

System.IO.Path.GetFullPath(@"..\..\")

Of course you would want to contain this inside some sort of validation/error handling logic.

nh43de
  • 813
  • 11
  • 11
13

If you want ot know what is the directory where your solution is located, you need to do this:

 var parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
            if (parent != null)
            {
                var directoryInfo = parent.Parent;
                string startDirectory = null;
                if (directoryInfo != null)
                {
                    startDirectory = directoryInfo.FullName;
                }
                if (startDirectory != null)
                { /*Do whatever you want "startDirectory" variable*/}
            }

If you let only with GetCurrrentDirectory() method, you get the build folder no matter if you are debugging or releasing. I hope this help! If you forget about validations it would be like this:

var startDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;
abel406
  • 359
  • 5
  • 9
9

Based on Gucu112's answer, but for .NET Core Console/Window application, it should be:

string projectDir = 
    Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."));

I'm using this in a xUnit project for a .NET Core Window Application.

zwcloud
  • 4,546
  • 3
  • 40
  • 69
8

If you really want to ensure you get the source project directory, no matter what the bin output path is set to:

  1. Add a pre-build event command line (Visual Studio: Project properties -> Build Events):

    echo $(MSBuildProjectDirectory) > $(MSBuildProjectDirectory)\Resources\ProjectDirectory.txt

  2. Add the ProjectDirectory.txt file to the Resources.resx of the project (If it doesn't exist yet, right click project -> Add new item -> Resources file)

  3. Access from code with Resources.ProjectDirectory.
FunctorSalad
  • 2,502
  • 25
  • 20
  • 2
    This is the only good answer here. Since I was using the directory for unit tests, I did this: echo $(ProjectDir)>$(ProjectDir)\Input\ProjectDir.txt I then included ProjectDir.txt as a unit test deployment item. No matter where the tests run, I now have the build folder. – Ed Bayiates Sep 23 '20 at 13:39
7

This solution works well for me, on Develop and also on TEST and PROD servers with ASP.NET MVC5 via C#:

var projectDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);

If you need project directory in project configuration file use:

$(ProjectDir)
Jan Sršeň
  • 1,045
  • 3
  • 23
  • 46
5
using System;
using System.IO;

// Get the current directory and make it a DirectoryInfo object.
// Do not use Environment.CurrentDirectory, vistual studio 
// and visual studio code will return different result:
// Visual studio will return @"projectDir\bin\Release\netcoreapp2.0\", yet 
// vs code will return @"projectDir\"
var currentDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

// On windows, the current directory is the compiled binary sits,
// so string like @"bin\Release\netcoreapp2.0\" will follow the project directory. 
// Hense, the project directory is the great grand-father of the current directory.
string projectDirectory = currentDirectory.Parent.Parent.Parent.FullName;
JeffreyYe_THU
  • 91
  • 2
  • 5
5
string projPath = Path.GetFullPath(@"..\..\..\");
Console.WriteLine(projPath);

This consistently works well for me. Give it a go.

Chroma
  • 77
  • 1
  • 6
5

I was looking for this too. I've got a project that runs HWC, and I'd like to keep the web site out of the app tree, but I don't want to keep it in the debug (or release) directory. FWIW, the accepted solution (and this one as well) only identifies the directory the executable is running in.

To find that directory, I've been using

string startupPath = System.IO.Path.GetFullPath(".\\").
Brett
  • 484
  • 6
  • 16
5

I had a similar situation, and after fruitless Googles, I declared a public string, which mods a string value of the debug / release path to get the project path. A benefit of using this method is that since it uses the currect project's directory, it matters not if you are working from a debug directory or a release directory:

public string DirProject()
{
    string DirDebug = System.IO.Directory.GetCurrentDirectory();
    string DirProject = DirDebug;

    for (int counter_slash = 0; counter_slash < 4; counter_slash++)
    {
        DirProject = DirProject.Substring(0, DirProject.LastIndexOf(@"\"));
    }

    return DirProject;
}

You would then be able to call it whenever you want, using only one line:

string MyProjectDir = DirProject();

This should work in most cases.

Rob
  • 45,296
  • 24
  • 122
  • 150
4

Another way to do this

string startupPath = System.IO.Directory.GetParent(@"./").FullName;

If you want to get path to bin folder

string startupPath = System.IO.Directory.GetParent(@"../").FullName;

Maybe there are better way =)

Tret
  • 75
  • 5
4

Yet another imperfect solution (but perhaps a little closer to perfect than some of the others):

    protected static string GetSolutionFSPath() {
        return System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName;
    }
    protected static string GetProjectFSPath() {
        return String.Format("{0}\\{1}", GetSolutionFSPath(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
    }

This version will return the current projects' folder even if the current project is not the Startup Project for the solution.

The first flaw with this is that I've skipped all error checking. That can be fixed easy enough but should only be a problem if you're storing your project in the root directory for the drive or using a junction in your path (and that junction is a descendant of the solution folder) so this scenario is unlikely. I'm not entirely sure that Visual Studio could handle either of these setups anyway.

Another (more likely) problem that you may run into is that the project name must match the folder name for the project for it to be found.

Another problem you may have is that the project must be inside the solution folder. This usually isn't a problem but if you've used the Add Existing Project to Solution option to add the project to the solution then this may not be the way your solution is organized.

Lastly, if you're application will be modifying the working directory, you should store this value before you do that because this value is determined relative to the current working directory.

Of course, this all also means that you must not alter the default values for your projects' Build->Output path or Debug->Working directory options in the project properties dialog.

krowe
  • 2,129
  • 17
  • 19
4

Try this, its simple

HttpContext.Current.Server.MapPath("~/FolderName/");
Hardeep Singh
  • 818
  • 9
  • 14
3

Use this to get the Project directory (worked for me):

string projectPath = 
    Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
perror
  • 7,071
  • 16
  • 58
  • 85
3

I have used following solution to get the job done:

string projectDir =
    Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\.."));
zwcloud
  • 4,546
  • 3
  • 40
  • 69
Gucu112
  • 877
  • 10
  • 12
3

Try:

var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);

This is solution different from the others does also take into account possible x86 or x64 build.

David Desmaisons
  • 986
  • 10
  • 15
  • This solution is almost there for the new csproj files too where the TargetFramework is included in the path. – Glenn Watson Jan 13 '19 at 21:42
  • 2
    For the new .netcore style format I had new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)(\\[a-zA-Z0-9.]*)?$", RegexOptions.Compiled) – Glenn Watson Jan 13 '19 at 21:52
3

After I had finally finished polishing my first answer regarding the us of public strings to derive an answer, it dawned on me that you could probably read a value from the registry to get your desired result. As it turns out, that route was even shorter:

First, you must include the Microsoft.Win32 namespace so you can work with the registry:

using Microsoft.Win32;    // required for reading and / or writing the registry

Here is the main code:

RegistryKey Projects_Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\9.0", false);
string DirProject = (string)Projects_Key.GetValue(@"DefaultNewProjectLocation");

A note on this answer:

I am using Visual Studio 2008 Professional Edition. If you are using another version, (i.e. 2003, 2005, 2010; etc.), then you mayt have to modify the 'version' part of the SubKey string (i.e. 8.0, 7.0; etc.).

If you use one of my answers, and if it is not too much to ask, then I would like to know which of my methods you used and why. Good luck.

  • dm
2

(Because 22 answers are not enough... here's one more....)

Mike Nakis posted a great answer, to which I added a few enhancements. This is just a slightly spiffed up version of his very nice code.

As Mike pointed out, this class file must be in the root of the project.

I did not run into any problems with the below, but perhaps there are nuances I'm not aware of. YMMV.

using System.IO;
using System.Runtime.CompilerServices;

namespace Whatever
{
  internal static class ProjectPathInfo
  {
    public static string CSharpClassFileName = nameof(ProjectPathInfo) + ".cs";
    public static string CSharpClassPath;
    public static string ProjectPath;
    public static string SolutionPath;

    static ProjectPathInfo() {
      CSharpClassPath = GetSourceFilePathName();
      ProjectPath = Directory.GetParent(CSharpClassPath)!.FullName;
      SolutionPath = Directory.GetParent(ProjectPath)!.FullName;
    }

    private static string GetSourceFilePathName( [CallerFilePath] string? callerFilePath = null ) => callerFilePath ?? "";
  }
}
Wellspring
  • 1,128
  • 1
  • 10
  • 19
2

Ok, 2021, a bit late to the party... but very annoyed by all possibilities I found in many projects:

  • bin/Debug
  • bin/x86/Debug
  • bin/Debug/net5.0-windows
  • ...

Come on... I just need a one-liner (or almost) to address some files in test units; I need to use it on all past, current, (maybe future) projects.

So, if the project name is the same of relative folder which it lies in:

  1. use the assembly name to pick project root folder name;
  2. go back until that name is found.

Code sample:

string appName = Assembly.GetExecutingAssembly().GetName().Name;
var dir = new DirectoryInfo(Environment.CurrentDirectory);
while (dir.Name != appName) {
  dir = Directory.GetParent(dir.FullName);
}
return dir.FullName;
jackomelly
  • 523
  • 1
  • 8
  • 15
1
/* /home/freephoenix888/Programming/csharpProject/bin/Debug/net7.0/csharpProject */
Console.WriteLine(Environment.CurrentDirectory);

/* /home/freephoenix888/Programming/csharpProject/ */
Console.WriteLine(Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.Parent.FullName);
FreePhoenix888
  • 4,510
  • 3
  • 13
  • 22
0

The best solution

string PjFolder1 =
    Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).
        Parent.Parent.FullName;

Other solution

string pjFolder2 = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)));

Test it, AppDomain.CurrentDomain.BaseDirectory worked for me on past project, now I get debug folder .... the selected GOOD answer just NOT WORK!.

//Project DEBUG folder, but STILL PROJECT FOLDER
string pjDebugFolder = AppDomain.CurrentDomain.BaseDirectory;

//Visual studio folder, NOT PROJECT FOLDER
//This solutions just not work
string vsFolder = Directory.GetCurrentDirectory();
string vsFolder2 = Environment.CurrentDirectory;
string vsFolder3 = Path.GetFullPath(".\\");   

//Current PROJECT FOLDER
string ProjectFolder = 
    //Get Debug Folder object from BaseDirectory ( the same with end slash)
    Directory.GetParent(pjDebugFolder).
    Parent.//Bin Folder object
    Parent. //Project Folder object
    FullName;//Project Folder complete path
0

This works on VS2017 w/ SDK Core MSBuild configurations.

You need to NuGet in the EnvDTE / EnvDTE80 packages.

Do not use COM or interop. anything.... garbage!!

 internal class Program {
    private static readonly DTE2 _dte2;

    // Static Constructor
    static Program() {
      _dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.15.0");
    }


    private static void FindProjectsIn(ProjectItem item, List<Project> results) {
      if (item.Object is Project) {
        var proj = (Project) item.Object;
        if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
          results.Add((Project) item.Object);
        else
          foreach (ProjectItem innerItem in proj.ProjectItems)
            FindProjectsIn(innerItem, results);
      }

      if (item.ProjectItems != null)
        foreach (ProjectItem innerItem in item.ProjectItems)
          FindProjectsIn(innerItem, results);
    }


    private static void FindProjectsIn(UIHierarchyItem item, List<Project> results) {
      if (item.Object is Project) {
        var proj = (Project) item.Object;
        if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
          results.Add((Project) item.Object);
        else
          foreach (ProjectItem innerItem in proj.ProjectItems)
            FindProjectsIn(innerItem, results);
      }

      foreach (UIHierarchyItem innerItem in item.UIHierarchyItems)
        FindProjectsIn(innerItem, results);
    }


    private static IEnumerable<Project> GetEnvDTEProjectsInSolution() {
      var ret = new List<Project>();
      var hierarchy = _dte2.ToolWindows.SolutionExplorer;
      foreach (UIHierarchyItem innerItem in hierarchy.UIHierarchyItems)
        FindProjectsIn(innerItem, ret);
      return ret;
    }


    private static void Main() {
      var projects = GetEnvDTEProjectsInSolution();
      var solutiondir = Path.GetDirectoryName(_dte2.Solution.FullName);

      // TODO
      ...

      var project = projects.FirstOrDefault(p => p.Name == <current project>);
      Console.WriteLine(project.FullName);
    }
  }
Latency
  • 426
  • 3
  • 12
0

I didn't see a solution by using string.Join and string.Split + SkipLast 4 elements, so here it is.

            string projectDir = 
            string.Join('/', AppDomain.CurrentDomain.BaseDirectory
                .Split(new char[] { '/' })
                .SkipLast(4));
-1

Try:

            {
                OpenFileDialog fd = new OpenFileDialog();
                fd.Multiselect = false;
                fd.Filter = "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|All files (*.*)|*.*";
                if (fd.ShowDialog() == true)
                {
                    if (fd.CheckFileExists)
                    {
                        var fileNameToSave = GetTimestamp(DateTime.Now) + Path.GetExtension(fd.FileName);
                        var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
                        var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);
                        var imagePath = Path.Combine(directory + @"\Uploads\" + fileNameToSave);
                        File.Copy(fd.FileName, imagePath);

                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

this is the code for uploading image into wpf upload directory

benson23
  • 16,369
  • 9
  • 19
  • 38
-7

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.FullName

Will give you the project directory.