How do I change the default path of IIS Express? - c#

Simply, how do I change the default path which IIS Express uses to write files too, etc.
It's currently set to C:\Program Files (x86)\IIS Express.
Note: I'm using Visual Studio 2019.
Code snippet:
System.IO.File.WriteAllText(#"file1.txt", "Test!");

Please try https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.setcurrentdirectory?view=netcore-2.2
public static void Main()
{
// Create string for a directory. This value should be an existing directory
// or the sample will throw a DirectoryNotFoundException.
string dir = #"C:\test";
try
{
//Set the current directory.
Directory.SetCurrentDirectory(dir);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("The specified directory does not exist. {0}", e);
}
// Print to console the results.
Console.WriteLine("Root directory: {0}", Directory.GetDirectoryRoot(dir));
Console.WriteLine("Current directory: {0}", Directory.GetCurrentDirectory());
}

Related

How to add path to PowerShell object in C#?

When calling GetPathToCmd below, I also want powerShell to consider some special directory - c:\scripts (passed as parameter). Is there a way to add that directory only to powerShell's PATH (i.e. $env:Path), without changing the path variable of the whole running process?
class Program {
static void Main(string[] args) {
string pathToCmd = GetPathToCmd("file-to-look-for.py", #"c:\scripts");
Console.WriteLine(pathToCmd ?? "Not found");
}
static string GetPathToCmd(string cmd, string alsoLookIn) {
using (PowerShell powerShell = PowerShell.Create()) {
// Anyway to add "alsoLookIn" to powerShell's path?
powerShell.AddCommand("get-command")
.AddArgument(new[] {$#".\{cmd}", cmd})
.AddParameter("Type", new[] {"Application", "ExternalScript"})
.AddParameter("ErrorAction", "Ignore")
;
CommandInfo commandInfo = powerShell.Invoke<CommandInfo>().FirstOrDefault();
return commandInfo?.Source;
}
}
}
You can change the $env:Path. However, the moment you do something like the below ...
# Modify current environment path for this session
$Env:Path = "$Env:Path;SomeNewFolderPath"
… then that $Env:Path change is there for the life of the session. It goes away when you start a new session.
However, you can do this on the fly, ensuring you don't clobber your original path this way
# Capture the current path
$CurrentPath = $Env:Path
C:\Program Files\Microsoft MPI\Bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;...
# Modify current environment path before entering the code segment
$Env:Path = "$Env:Path;SomeNewFolderPath"
$Env:Path
C:\Program Files\Microsoft MPI\Bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;...;SomeNewFolderPath
# Modify current environment path after leaving the code segment
$Env:Path = $CurrentPath
$Env:Path
C:\Program Files\Microsoft MPI\Bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;...

Show C# reference documentation in intellisense

If I create a List list.. Visual Studio offers its members with intellisense, but there is no documentation for the members. If I go to the definition of List, I see the following:
[DefaultMember("Item")]
public class List<T> : IEnumerable, ICollection, IList, ICollection<T>, IEnumerable<T>, IList<T>
{
// ...
public void Add(T item);
public void Clear();
public bool Contains(T item);
// ...
}
There is no comments/descriptions for any of the members. This applies to any other core classes.
What can I do to make Visual Studio 2017 show the documentation so I don't have to Alt+Tab to the official C# reference documentation website any time I want to know what a method does?
Is there any SDK library I have to add in order to have documentation?
I'm using Visual Studio on Unity projects.
You can do this but you have to know two things
1.Where Unity's framework dll are located:
When "Scripting Runtime Version" is set to ".NET 3.5 Equivalent" in the Editor, the C# DLL API used is at:
<UnityInstallationDirecory>\Editor\Data\MonoBleedingEdge\lib\mono\unity
When "Scripting Runtime Version" is set to ".NET 4.x Equivalent" in the Editor, the latest framework is used the path ends with the framework version:
<UnityInstallationDirecory>\Editor\Data\MonoBleedingEdge\lib\mono\<API-version>
This path may change in the future. To find the current path to the dll Unity is using, simply expand the Assembly and References in the "Solution Explorer" tab in Visual Studio then select one of the C# DLL. In the example below, System.dll is selected, the path will be displayed under the property.
2.Where the C# standard framework dll are located:
When using ".NET 3.5 Equivalent" in the Unity Editor, the corresponding C# framework API used is at:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5\Profile\Client
When using ".NET 4.x Equivalent" in the Unity Editor, the corresponding C# framework API used is at:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\<API-version>
Showing C# core documentation in Visual Studio:
Now that you know the locations, notice that each dll in the standard framework location from #2 has a complimentary xml file that ends with .xml extension. For example, the System.Core.dll dll, has complementary file named System.Core.xml in the-same folder. Each xml file contains the documentation for each corresponding dll file.
All you have to do is copy xml file for each dll file from the standard framework location into Unity's framework dll location. Restart Visual Studio and documentation should be working.
This is time consuming to do manually so I made an Editor plugin to handle it. Enable it by going to the Programmer-->Enable Core Documentation menu and disable it by going to the Programmer-->Disable Core Documentation menu. You must restart Visual Studio in order for this to take effect.
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
public class DocEnabler : MonoBehaviour
{
//Replace both with the proper paths on your system
static string unityFrameworkPath = #"G:\Applications\Unity\Editor\Data\MonoBleedingEdge\lib\mono\unity";
static string stdCoreFrameworkPath = #"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5\Profile\Client";
[MenuItem("Programmer/Enable Core Documentation")]
static void EnableCoreDoc()
{
CopyFilesByExt(stdCoreFrameworkPath, unityFrameworkPath, "xml");
}
[MenuItem("Programmer/Disable Core Documentation")]
static void DisableCoreDoc()
{
DeleteFilesByExt(unityFrameworkPath, "xml");
}
static void DeleteFilesByExt(string path, string ext)
{
DirectoryInfo drctyInfo = new DirectoryInfo(path);
FileInfo[] files = drctyInfo.GetFiles("*." + ext)
.Where(p => p.Extension == "." + ext).ToArray();
foreach (FileInfo file in files)
{
try
{
file.Attributes = FileAttributes.Normal;
file.Delete();
//File.Delete(file.FullName);
}
catch (Exception e)
{
Debug.Log("Error while deleting file: " + file.Name + "\r\n" + e.Message);
}
}
DoneMessage();
}
static void CopyFilesByExt(string source, string destPath, string ext)
{
DirectoryInfo drctyInfo = new DirectoryInfo(source);
FileInfo[] files = drctyInfo.GetFiles("*." + ext)
.Where(p => p.Extension == "." + ext).ToArray();
foreach (FileInfo file in files)
{
try
{
string fromPath = file.FullName;
string toPath = Path.Combine(destPath, file.Name);
file.CopyTo(toPath, true);
//File.Copy(fromPath, toPath, true);
}
catch (Exception e)
{
Debug.Log("Error while Copying file: " + file.Name + "\r\n" + e.Message);
}
}
DoneMessage();
}
static void DoneMessage()
{
Debug.Log("Action complete. Restart Visual Studio for the changes to take effect");
}
}
Coming to this in 2021. Programmer's solution still works, but the locations have changed and there is another copy that needs to happen to support netstandard 2.0.
I hope Programmer doesn't mind but I adjusted the script with the changed default locations and added the netstandard 2.0 locations. JetBrains Rider has the same problem and solution.
My experience in this field is 2 days strong, so use with caution. But it solved all of my problems.
EDIT: I discovered that not only can these dir names vary among systems, but Windows doesn't ship with the netstandard reference by default. I'll correct this post when I find where it came from.
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
public class DocEnabler : MonoBehaviour
{
//Replace both with the proper paths on your system
// .NET 4.x
static string unityFrameworkPath = #"C:\Program Files\Unity\Hub\Editor\2021.1.5f1\Editor\Data\MonoBleedingEdge\lib\mono\4.7.1-api";
static string microsoftFrameworkPath = #"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.X";
// .NETSTANDARD 2.0
static string unityNetStandardPath = #"C:\Program Files\Unity\Hub\Editor\2021.1.5f1\Editor\Data\NetStandard\ref\2.0.0";
static string microsoftNetStandardPath = #"C:\Program Files\dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1";
[MenuItem("Programmer/Enable Core Documentation")]
static void EnableCoreDoc()
{
CopyFilesByExt(microsoftFrameworkPath, unityFrameworkPath, "xml");
CopyFilesByExt(microsoftNetStandardPath, unityNetStandardPath, "xml");
}
[MenuItem("Programmer/Disable Core Documentation")]
static void DisableCoreDoc()
{
DeleteFilesByExt(unityFrameworkPath, "xml");
DeleteFilesByExt(unityNetStandardPath, "xml");
}
static void DeleteFilesByExt(string path, string ext)
{
DirectoryInfo dirInfo = new DirectoryInfo(path);
FileInfo[] files = dirInfo.GetFiles("*." + ext)
.Where(p => p.Extension == "." + ext).ToArray();
foreach (FileInfo file in files)
{
try
{
file.Attributes = FileAttributes.Normal;
file.Delete();
}
catch (Exception e)
{
Debug.Log("Error while deleting file: " + file.Name + "\r\n" + e.Message);
}
}
DoneMessage();
}
static void CopyFilesByExt(string source, string destPath, string ext)
{
DirectoryInfo dirInfo = new DirectoryInfo(source);
FileInfo[] files = dirInfo.GetFiles("*." + ext)
.Where(p => p.Extension == "." + ext).ToArray();
foreach (FileInfo file in files)
{
try
{
string toPath = Path.Combine(destPath, file.Name);
file.CopyTo(toPath, true);
}
catch (Exception e)
{
Debug.Log("Error while Copying file: " + file.Name + "\r\n" + e.Message);
}
}
DoneMessage();
}
static void DoneMessage()
{
Debug.Log("Action complete. Restart Visual Studio for the changes to take effect");
}
}
I would've posted as a comment and included some proof images, but I don't have enough karma yet.
Here's a link to an image of it working on a .NET 2.0 project in Visual Studio.
I found an answer in the Unity Answers site Here.
Answer by Blue_Ninja0 · Sep 21, 2017 at 09:41 PM
It has been brought to my attention that Unity doesn't include the System.xml file required for Intellisense documentation for their old mono runtime.
It seems from Unity 2017 onwards, as long as you enable .NET 4.6 on the API Compatibility Level setting on the Player Settings, you will get full documentation. I have tested and it worked fine.

Directory Check Won't Work

I tried creating a program that tells you if a directory exists or not, but no matter what I input, it always comes up as not existing.
My Code:
using System;
using System.IO;
class TestFileAndDirectory
{
public static void Main()
{
string input;
input = Console.ReadLine();
if ( Directory.Exists(input))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't Exist");
}
Console.ReadLine();
}
}
At first I just thought maybe it was my logic, so I tried this code from the book: Microsoft Visual C# 2010: Comprehensive Ch.14:
using System;
using System.IO;
public class DirectoryInformation
{
public static void Main()
{
string directoryName;
string[] listOfFiles;
Console.Write("Enter a folder >> ");
directoryName = Console.ReadLine();
if(Directory.Exists(directoryName))
{
Console.WriteLine("Directory exists, " +
"and it contains the following:");
listOfFiles = Directory.GetFiles(directoryName);
for(int x = 0; x < listOfFiles.Length; ++x)
Console.WriteLine(" {0}", listOfFiles[x]);
}
else
{
Console.WriteLine("Directory does not exist");
}
}
}
When I tried this code it did not work either not even if I put it into the same base folder as the directory I'm trying to find.
Path in question: C:\C#\Chapter.14\Cat Haikus
Path of Program: C:\C#\Chapter.14\TestFilesAndDirectories.cs
The path parameter is permitted to specify relative or absolute path
information. Relative path information is interpreted as relative to
the current working directory.
Source: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
If your input string is only a folder name like "Chapter. 14" (relative path), then this folder must exist in the path of your executable file. Like PathOfTheExecutableFile\Chapter. 14.
If the folder is in a completely different place, use absolute paths. Like C:\Users\theuser\Desktop\Chapter. 14.
Update:
Since you want to check C:\C#\Chapter.14\Cat Haikus folder, you could check if it exists using
if (Directory.Exists(#"C:\C#\Chapter.14\Cat Haikus")){
Console.WriteLine("Exists");
}
I don't know your exact folder tree structure, but if your executable file is in a subfolder of C:\C#\Chapter.14\, you could also use Directoy.GetParent() method.

After updating EnvironmentVariable - PATH - I still get a FileNotFoundException on Windows 2003 Server

I'm just starting with a new product and I guess I don't understand the PATH variable. My documentation says to update the PATH like this which I do successfully in a little console application:
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff();
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
In the above project, I have a reference to HP.HPTRIM.SDK which exists at:
C:\Program Files\Hewlett-Packard\HP TRIM\HP.HPTRIM.SDK.dll
After the above ran successfully, I tried to permanently change the PATH by using Control Panel:System:Advanced:Environment Variables. I verified the above PATH by examining the registry at HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment. I see the following as the last entry in the PATH value:
;C:\Program Files\Hewlett-Packard\HP TRIM\
I thought this would permanently SET this at the end of the PATH but when I run the above console program with a few lines commented out I get the FileNotFoundException (see below). I am confused about how to get this in the PATH and not have to worry about it anymore.
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
//string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
//string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
//Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff(); // without setting the PATH this fails despite being in REGISTRY...
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
Only newly started processes that don't inherit their environment from their parent will have the updated PATH. You'll have to at least restart the Visual Studio hosting process, close and re-open your solution. To cover all possible corners, log out and log back in so that Windows Explorer (and thus Visual Studio) also start using the updated environment.

How do I get/set a winforms application's working directory?

To get the Application's root I am Currently using:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)
But that feels sloppy to me. Is there a better way to get the root directory of the application and set that to the working directory?
So, you can change directory by just using Envrionment.CurrentDirectory = (sum directory). There are many ways to get the original executing directoy, one way is essentially the way you described and another is through Directory.GetCurrentDirectory() if you have not changed the directory.
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
// Get the current directory.
string path = Directory.GetCurrentDirectory();
string target = #"c:\temp";
Console.WriteLine("The current directory is {0}", path);
if (!Directory.Exists(target))
{
Directory.CreateDirectory(target);
}
// Change the current directory.
Environment.CurrentDirectory = (target);
if (path.Equals(Directory.GetCurrentDirectory()))
{
Console.WriteLine("You are in the temp directory.");
}
else
{
Console.WriteLine("You are not in the temp directory.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
ref
What is it that you want; the working directory, or the directory in which the assembly is located?
For the current directory, you can use Environment.CurrentDirectory. For the directory in which the assembly is located, you can use this:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

Categories

Resources