How to set file version comment - c#

Where can I set the file version comments..?
We can get it by
FileVersionInfo fv =
System.Diagnostics.FileVersionInfo.GetVersionInfo(
Assembly.GetExecutingAssembly().Location);
var comment = fv.Comments;
Then how can I set it so that I can show the same somewhere..

For .NET Assemblies you can set the File Version Comments using the AssemblyDescriptionAttribute, which you usually put in the AssemblyInfo.cs file in your project when using Visual Studio.
[assembly: AssemblyDescription("The assembly does xxx by yyy")]
For other types of executables the file version is set using a resource in the file.
The different assembly level File Version attributes maps as follows:
FileVersionInfo.Comments = AssemblyDescription
FileVersionInfo.CompanyName = AssemblyCompany
FileVersionInfo.FileDescription = AssemblyTitle
FileVersionInfo.FileVersion = AssemblyFileVersion
FileVersionInfo.LegalCopyright = AssemblyCopyright
FileVersionInfo.LegalTrademarks = AssemblyTrademark
FileVersionInfo.ProductName = AssemblyProduct
FileVersionInfo.ProductVersion = AssemblyInformationalVersion

Nowadays in .Net 6
you can set comments in*.csproj
<Description>My Comment</Description>
And get
public static string GetComments()
{
var fileName = Assembly.GetEntryAssembly()?.Location;
if (fileName == null) return String.Empty;
var versionInfo = FileVersionInfo.GetVersionInfo(fileName);
return versionInfo?.Comments ?? String.Empty;
}

To set this value, you can edit the AssemblyInfo.cs file of your project.
This line is what you are looking for:
[assembly: AssemblyDescription("This is the comment")]

Related

How to get AssemblyInformations

In my AssemblyInfo.cs file, I have attributes like:
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyCopyright("Copyright © 2015")]
Now i want to get this informations in my OnLaunched(LaunchActivatedEventArgs e) Method in my App.xaml.cs.
When I search for this in the internet and on SO I always solutions like:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;
But this doesn´t work for Windows 10. So is there something similar for Windows 10?
Edit:
I am developing an Windows 10 UWP application.
If you need to get information about app version in general, you can use Package.Current property.
using Windows.ApplicationModel;
Package package = Package.Current;
PackageId packageId = package.Id;
PackageVersion version = packageId.Version;
String output = String.Format(
"Name: \"{0}\"\n" +
"Version: {1}.{2}.{3}.{4}\n" +
"Architecture: {5}\n" +
"ResourceId: \"{6}\"\n" +
"Publisher: \"{7}\"\n" +
"PublisherId: \"{8}\"\n" +
"FullName: \"{9}\"\n" +
"FamilyName: \"{10}\"\n" +
"IsFramework: {11}",
packageId.Name,
version.Major, version.Minor, version.Build, version.Revision,
packageId.Architecture,
packageId.ResourceId,
packageId.Publisher,
packageId.PublisherId,
packageId.FullName,
packageId.FamilyName,
package.IsFramework);
You can find attributes using this code:
var currentAsembly = typeof(App).GetTypeInfo().Assembly;
var customAttributes = currentAssembly.CustomAttributes;
CustomAttributes is IEnumerable object of available atttributes among them you can find information abut assembly and file version
Edit:
Here is complete code:
var currentAssembly = typeof(App).GetTypeInfo().Assembly;
var customAttributes = currentAssembly.CustomAttributes;
var list = customAttributes.ToList();
var res = list[0];
var result = list.FirstOrDefault(x => x.AttributeType.Name == "AssemblyFileVersionAttribute");
var ver = result.ConstructorArguments[0].Value;

Cannot find the embedded schemas in the assembly

I have DefaultSchemaSet.xsd. Now I'm getting FileNotFoundException for the codes below. Give me any suggestion, please? May I know how to solve this?
public static void GetDefaultSchemas(string path, XmlSchemaSet schemas, ValidationEventHandler schemaValidationEventHandler)
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
{
if (stream == null)
{
throw new FileNotFoundException("Cannot find the embedded schemas in the assembly!");
}
var schema = XmlSchema.Read(stream, schemaValidationEventHandler);
schemas.Add(schema);
}
}
Check the format of the resource name:
DefaultNamespace[.Subfolder][...MoreSubfolers].FileName[.extension]
You need to set Build Action to Embedded Resource in project's file's properties.
Also, you need to check the namespace you use for your project:
Try to examine the available resources, so you can find if a particular one present:
var executingAssembly = Assembly.GetExecutingAssembly();
var resourceNames = executingAssembly.GetManifestResourceNames();
foreach (var resourceName in resourceNames)
{
Console.WriteLine("Resource: " + resourceName);
Console.WriteLine("Contents:");
using (var sr = new StreamReader(executingAssembly.GetManifestResourceStream(resourceName)))
{
Console.WriteLine(sr.ReadToEnd());
}
}
Output:
Resource: EmbeddingTests.TextFile1.txt
Contents:
Hello
Resource: EmbeddingTests.NewFolder1.TextFile2.txt
Contents:
Hello 2
In order to make sure you can access it from your code you need to ensure that the file's build action is set to "Embedded Resource"
To help further we really need to see where the file lies in your solution (to give you an exact answer), however in the mean time if you ensure that your parameter "path" follows the pattern:
[DefaultNamespace].[AnySubFolders].[filename.fileextension]
note without the square brackets

Guaranteed way to find the filepath of the ildasm.exe and ilasm.exe files regardless of .NET version/environment?

Is there a way to programmatically get the FileInfo/Path of the ildasm.exe/ilasm.exe executables? I'm attempting to decompile and recompile a dll/exe file appropriately after making some alterations to it (I'm guessing PostSharp does something similar to alter the IL after the compilation).
I found a blog post that pointed to:
var pfDir = Environment.GetFolderPath(Environment.SpecialFolders.ProgramFiles));
var sdkDir = Path.Combine(pfDir, #"Microsoft SDKs\Windows\v6.0A\bin");
...
However, when I ran this code the directory did not exist (mainly because my SDK version is 7.1), so on my local machine the correct path is #"Microsoft SDKs\Windows\v7.1\bin". How do I ensure I can actually find the ildasm.exe?
Similarly, I found another blog post on how to get access to ilasm.exe as:
string windows = Environment.GetFolderPath(Environment.SpecialFolder.System);
string fwork = Path.Combine(windows, #"..\Microsoft.NET\Framework\v2.0.50727");
...
While this works, I noticed that I have Framework and Framework64, and within Framework itself I have all of the versions up to v4.0.30319 (same with Framework64). So, how do I know which one to use? Should it be based on the .NET Framework version I'm targetting?
Summary:
How do I appropriately guarantee to find the correct path to ildasm.exe?
How do I appropriately select the correct ilasm.exe to compile?
One option would be to reference Microsoft.Build.Utilities.Core and use:
var ildasm = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("ildasm.exe", TargetDotNetFrameworkVersion.VersionLatest);
var ilasm = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFrameworkFile("ilasm.exe", TargetDotNetFrameworkVersion.VersionLatest);
Right now on my machine this returns:
ildasm = C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\ildasm.exe
ilasm = C:\Windows\Microsoft.NET\Framework\v4.0.30319\ilasm.exe
I recently needed to do this so I trawled the interwebs for all the possible paths of the Windows SDK and search through those in most recent known order. I also check for whether the OS and process is 64bit and then just use that version by looking in the appropriate Program Files folders. I don't think choosing 64-bit over the 32-bit versions of the tools has any great significance. The x86 version of ILAsm can happily assemble 64-bit preferred assemblies without a hitch, it's all IL and not actually executing any of the code.
ILDasm is part of the Windows SDK where ILAsm is just the .NET Framework SDK so here are some static methods to hunt them down with. The code is baked for .NET 4.0 but you could make some minor tweaks to get it building on .NET 2.0 if you want.
// ILDasm.exe will be somewhere in here
private static string FindPathForWindowsSdk()
{
string[] windowsSdkPaths = new[]
{
#"Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\",
#"Microsoft SDKs\Windows\v8.0A\bin\",
#"Microsoft SDKs\Windows\v8.0\bin\NETFX 4.0 Tools\",
#"Microsoft SDKs\Windows\v8.0\bin\",
#"Microsoft SDKs\Windows\v7.1A\bin\NETFX 4.0 Tools\",
#"Microsoft SDKs\Windows\v7.1A\bin\",
#"Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\",
#"Microsoft SDKs\Windows\v7.0A\bin\",
#"Microsoft SDKs\Windows\v6.1A\bin\",
#"Microsoft SDKs\Windows\v6.0A\bin\",
#"Microsoft SDKs\Windows\v6.0\bin\",
#"Microsoft.NET\FrameworkSDK\bin"
};
foreach (var possiblePath in windowsSdkPaths)
{
string fullPath = string.Empty;
// Check alternate program file paths as well as 64-bit versions.
if (Environment.Is64BitProcess)
{
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), possiblePath, "x64");
if (Directory.Exists(fullPath))
{
return fullPath;
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), possiblePath, "x64");
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), possiblePath);
if (Directory.Exists(fullPath))
{
return fullPath;
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), possiblePath);
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
// ILAsm.exe will be somewhere in here
private static string FindPathForDotNetFramework()
{
string[] frameworkPaths = new[]
{
#"Microsoft.NET\Framework\v4.0.30319",
#"Microsoft.NET\Framework\v2.0.50727"
};
foreach (var possiblePath in frameworkPaths)
{
string fullPath = string.Empty;
if (Environment.Is64BitProcess)
{
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), possiblePath.Replace(#"\Framework\", #"\Framework64\"));
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), possiblePath);
if (Directory.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
You can augment this by passing in the executable you are looking for and change Directory.Exists with File.Exists as well, up to you. You could also take the possible lists and put them in a config file so you can add more without recompiling.

c# how to print AssemblyFileVersion

How can I print in my log the version of the program that is running?
In other words, can I access AssemblyFileVersion using Console.WriteLine?
Thanks
Tony
It looks like something like this would work:
public static string Version
{
get
{
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
return String.Format("{0}.{1}", fvi.ProductMajorPart, fvi.ProductMinorPart);
}
}
From another post on SO.
// Get the version of the current application.
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName assemName = assem.GetName();
Version ver = assemName.Version;
Console.WriteLine("{0}, Version {1}", assemName.Name, ver.ToString());
More on MSDN:
Version Class
FileVersionInfo.GetVersionInfo(asm.Location) doesn't work for embedded assemblies (e.g. using Fody's Costura to ship a single EXE instead of the executable and all of it's dependent assemblies). In which case, the following works as a fallback:
var assembly = Assembly.GetExecutingAssembly();
var fileVersionAttribute = assembly.CustomAttributes.FirstOrDefault(ca => ca.AttributeType == typeof(AssemblyFileVersionAttribute));
if (fileVersionAttribute != null && fileVersionAttribute.ConstructorArguments.Any())
return fileVersionAttribute.ConstructorArguments[0].ToString().Replace("\"","");
return string.Empty;

How do you get the current project directory from C# code when creating a custom MSBuild task?

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.
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;
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
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.
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.
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.
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;
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.
If you really want to ensure you get the source project directory, no matter what the bin output path is set to:
Add a pre-build event command line (Visual Studio: Project properties -> Build Events):
echo $(MSBuildProjectDirectory) > $(MSBuildProjectDirectory)\Resources\ProjectDirectory.txt
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)
Access from code with Resources.ProjectDirectory.
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)
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(".\\").
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;
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.
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 =)
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.
Try this, its simple
HttpContext.Current.Server.MapPath("~/FolderName/");
string projPath = Path.GetFullPath(#"..\..\..\");
Console.WriteLine(projPath);
This consistently works well for me. Give it a go.
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
Use this to get the Project directory (worked for me):
string projectPath =
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
I have used following solution to get the job done:
string projectDir =
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\.."));
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.
(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 ?? "";
}
}
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:
use the assembly name to pick project root folder name;
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;
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
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);
}
}
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));
/* /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);
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
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.FullName
Will give you the project directory.

Categories

Resources