[英]Changing the base path of an assembly from the bin directory to a different directory
I have a Test.cs file in C:\\ This test file reads from an input file and writes the same to an output file. 我在C:\\中有一个Test.cs文件。该测试文件从输入文件读取并将其写入输出文件。 Test.cs
Test.cs
public class Test
{
public static int Main(string[] args)
{
var reader = new StreamReader("in.txt");
string input = reader.ReadLine();
var writer = new StreamWriter("out.txt");
writer.WriteLine(input);
return 0;
}
}
Here it should be noted that the code only uses the filename and not the full file path , which means the file is expected to be in the directory where the program is running. 此处应注意,该代码仅使用文件名 , 而不使用完整的文件路径 ,这意味着该文件应位于程序运行的目录中。 And I have created the in.txt in C:\\
并且我在C:\\中创建了in.txt。
Now, there is ac# code called Runner.cs in a solution in C:\\Project\\Runner.cs , that dynamically compiles the Test.cs code and runs it using reflection. 现在,在C:\\ Project \\ Runner.cs的解决方案中,有一个名为Runner.cs的 ac#代码,该代码可以动态编译 Test.cs代码并使用反射运行它。 Now, when the Test.cs runs, it expects the in.txt file to be in C:\\Project\\bin\\Debug\\in.txt , but it is actually present in C:\\in.txt
现在,当Test.cs运行时,它希望in.txt文件位于C:\\ Project \\ bin \\ Debug \\ in.txt中 ,但实际上它存在于C:\\ in.txt中
So, my question is, is there a way to make the code to get the file from C:\\in.txt and not from the bin directory without changing the path of the file in the Test.cs code file. 因此,我的问题是,有没有一种方法可以使代码从C:\\ in.txt而不是从bin目录中获取文件,而无需更改Test.cs代码文件中文件的路径 。
Edit: It is my bad that I forgot to mention why I am in need of this requirement. 编辑:忘记提及为什么我需要此要求对我来说是很不好的。
The Test.cs file comes from over the wire. Test.cs文件来自网络。 And I felt it will not be a good choice to edit this file and set the file path accordingly.
我觉得编辑该文件并相应地设置文件路径不是一个好选择。 I want to compile it and run it as it is.
我想编译并按原样运行。
I hope I am clear. 我希望我清楚。 If not, please feel free to ask for more information.
如果没有,请随时询问更多信息。
If it is as simple as you show in your code switching the CurrentDirectory works for this example: 如果它像您在代码中显示的那样简单,则CurrentDirectory适用于此示例:
var mainMembers = new CSharpCodeProvider()
.CreateCompiler()
.CompileAssemblyFromSource(
new CompilerParameters { GenerateInMemory = true }
, @"
using System;
using System.IO;
public class M {
public static int Main() {
Console.WriteLine(""CurDir = ""+ Environment.CurrentDirectory);
var reader = new StreamReader(""in.txt"");
string input = reader.ReadLine();
var writer = new StreamWriter(""out.txt"");
writer.WriteLine(input);
return 0;
}
}")
.CompiledAssembly
.GetType("M")
.GetMember("Main");
// inspect
Environment.CurrentDirectory.Dump("current");
// keep
var oldcd = Environment.CurrentDirectory;
// switch
Environment.CurrentDirectory = "c:\\temp";
// invoke external code
((MethodInfo) mainMembers[0]).Invoke(null,null);
// restore
Environment.CurrentDirectory = oldcd;
In a multi threaded scenario this becomes unreliable. 在多线程方案中,这变得不可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.