How to compile code in C# Dot Net on run time? - c#

So I would like to compile a whole folder of .cs files and then create a DLL file and then use that DLL in my project on runtime.
I searched the internet and found out CSharpCodeProvider can help me in this.
But what got me confused is that most of the example on this site showed how to read one single file, not a folder as whole.
So I am assuming that my folder containing the .cs files will be linked together.
Example Files:
File: TestMain.cs
class TestMain
{
public static void Main(string[] args)
{
Test t = new Test();
t.Hello();
}
}
File: Test.cs
public class Test
{
public void Hello()
{
Console.Write(#"Hello");
}
}
Any guidance will be well appreciated.

Ok So after searching and guidance here is my working code:
public static Assembly CompileAssembly(string[] sourceFiles, string outputAssemblyPath)
{
var codeProvider = new CSharpCodeProvider();
var compilerParameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = false,
OutputAssembly = outputAssemblyPath
};
// Add CSharpSimpleScripting.exe as a reference to Scripts.dll to expose interfaces
//compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles); // Compile
if (result.Errors.Count > 0)
{
MessageBox.Show(#"Error Occured");
}
else
{
return result.CompiledAssembly;
}
return null;
}

Basically, You can use CodeDom.Compiler to compile the dll, i wrote somethinglike this long back then use Reflection later to reference it dynamically
//dot net compiler
using System;
using System.CodeDom.Compiler;
using System.IO;
namespace IndiLogix.dotCompiler
{
class dotCompiler
{
FileInfo sourceFile;// = new FileInfo(sourceName);
CodeDomProvider provider = null;
bool compileOk = false;
// Compile Executable
public bool CompileExecutable(String sourceName)
{
sourceFile = new FileInfo(sourceName);
I_GetProvider(sourceFile);
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
//return "CSharp";
}
if (provider != null)
{
// Format the executable file name.
// Build the output assembly path using the current directory
// and _cs.exe or _vb.exe.
String exeName = String.Format(#"{0}\{1}.exe",
System.Environment.CurrentDirectory,
sourceFile.Name.Replace(".", "_"));
string dllName = String.Format(#"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of a class library.
cp.GenerateExecutable = true;
// Specify the assembly file name to generate.
cp.OutputAssembly = exeName;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Invoke compilation of the source file.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
string temp;
if (cr.Errors.Count > 0)
{
// Display compilation errors.
temp = sourceName + "\n" + cr.PathToAssembly;
foreach (CompilerError ce in cr.Errors)
{
temp += "\nError:" + ce.ToString();
}
System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK);
}
else
{
// Display a successful compilation message.
//Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly);
System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly,"dotCompiler:)",System.Windows.Forms.MessageBoxButtons.OK);
}
// Return the results of the compilation.
if (cr.Errors.Count > 0)
{
compileOk = false;
}
else
{
compileOk = true;
}
}
return compileOk;
}
private void I_GetProvider(FileInfo sourceFile)
{
// Select the code provider based on the input file extension.
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
}
else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB")
{
provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic");
}
else
{
//Console.WriteLine("Source file must have a .cs or .vb extension");
//_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error);
System.Windows.Forms.MessageBox.Show(
"Source file must have *.cs or *.vb extension", "dotCompiler Error",
System.Windows.Forms.MessageBoxButtons.OK);
}
}
private string I_GetProvider_RetStr(FileInfo sourceFile)
{
// Select the code provider based on the input file extension.
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
return "CSharp";
}
else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB")
{
provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic");
return "VisualBasic";
}
else
{
//Console.WriteLine("Source file must have a .cs or .vb extension");
//_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error);
return "Source file must have *.cs or *.vb extension";
}
}
public bool CompileDll(String sourceName)
{
sourceFile = new FileInfo(sourceName);
I_GetProvider(sourceFile);
if (provider != null)
{
// Format the executable file name.
// Build the output assembly path using the current directory
// and _cs.exe or _vb.exe.
String exeName = String.Format(#"{0}\{1}.exe",
System.Environment.CurrentDirectory,
sourceFile.Name.Replace(".", "_"));
string dllName = String.Format(#"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of a class library.
cp.GenerateExecutable = false;
// Specify the assembly file name to generate.
cp.OutputAssembly = dllName;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Invoke compilation of the source file.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
string temp;
if (cr.Errors.Count > 0)
{
// Display compilation errors.
temp = "compiling " + sourceName + " to " + cr.PathToAssembly;
foreach (CompilerError ce in cr.Errors)
{
temp += "\nError:" + ce.ToString();
}
System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK);
}
else
{
// Display a successful compilation message.
//Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly);
System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly, "dotCompiler:)", System.Windows.Forms.MessageBoxButtons.OK);
}
// Return the results of the compilation.
if (cr.Errors.Count > 0)
{
compileOk = false;
}
else
{
compileOk = true;
}
}
return compileOk;
}
}
}

string sourceCode = #"
public class Test
{
public void Hello()
{
Console.Write(#'Hello');
}
}";
var compParms = new CompilerParameters{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, sourceCode);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("Test");
MethodInfo mi = typeInstance.GetType().GetMethod("Hello");
mi.Invoke(typeInstance, null);
Console.ReadLine();

Related

HealthKit capabilities are not adding through unity c# script

Can anyone help me to resolve my healthKit capability issue for a unity app.
I am trying to add healthKit capability to my unity app. I am using BEHEALTHKIT and HealthKitBuildProcessor.cs editor class to add capability and other dependencies. Following are the code I am using .But for some reason healthkit Capability and entitlements are not adding through this code (permission parameters are adding to plist), and returning null when I print Debug.Log("newEntitlements: " + newEntitlements);Also my build failing with an error saying "provisioning profile doesn't support the HealthKit Capability"
I have already added HealthKit capability for the profile from developer.apple.com.
Unity version: 2019.4.4f1
public class HealthKitBuildProcessor : IProcessSceneWithReport
{
private static string shareString = null;
private static string updateString = null;
private static string clinicalString = null;
/*! #brief required by the IProcessScene interface. Set high to let other postprocess scripts run first. */
public int callbackOrder {
get { return 100; }
}
/*! #brief Searches for HealthKitDataTypes objects & reads the usage strings for the OnPostprocessBuild phase.
#param scene the scene being processed.
#param report a report containing information about the current build
*/
public void OnProcessScene(Scene scene, BuildReport report) {
GameObject[] rootObjects = scene.GetRootGameObjects();
foreach (GameObject obj in rootObjects) {
HealthKitDataTypes types = obj.GetComponentInChildren<HealthKitDataTypes>();
if (types != null) {
if (types.AskForSharePermission()) {
HealthKitBuildProcessor.shareString = types.healthShareUsageDescription;
}
if (types.AskForUpdatePermission()) {
HealthKitBuildProcessor.updateString = types.healthUpdateUsageDescription;
}
/*if (types.AskForClinicalPermission()) {
HealthKitBuildProcessor.clinicalString = types.clinicalUsageDescription;
}*/
}
}
}
/*! #brief Updates the Xcode project.
#param buildTarget the target build platform
#param path the path of the target build
*/
[PostProcessBuildAttribute(10)]
public static void OnPostprocessBuild(BuildTarget buildTarget, string path) {
Debug.Log("--- BEHEALTHKIT POST-PROCESS BUILD ---");
if (buildTarget == BuildTarget.iOS) {
//string projPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj";
//Debug.Log("BE:PROJECT PATH :" + projPath);
var projPath = PBXProject.GetPBXProjectPath(path);
var proj = new PBXProject();
proj.ReadFromString(System.IO.File.ReadAllText(projPath));
#if UNITY_2019_3_OR_NEWER
string mainTarget = proj.GetUnityMainTargetGuid();
string frameworkTarget = proj.GetUnityFrameworkTargetGuid();
Debug.Log("--- BE: UNITY_2019_3_OR_NEWER ---");
Debug.LogFormat("main target: {0}", mainTarget);
Debug.LogFormat("framework target: {0}", frameworkTarget);
#else
string targetName = PBXProject.GetUnityTargetName();
string mainTarget = proj.TargetGuidByName(targetName);
Debug.Log("---BE: ELSE UNITY_2019_3_OR_NEWER ---");
Debug.Log("main target: {0}", mainTarget);
Debug.Log("targetName: ", targetName);
#endif
bool addHealthRecordsCapability = (clinicalString != null);
//Debug.Log("addHealthRecordsCapability: ", addHealthRecordsCapability);
// Info.plist
//-----------
Debug.Log("---BE: PLIST ---");
var info = ProcessInfoPList(path, addHealthRecordsCapability);
// Entitlements
//--------------
Debug.Log("---BE: ProcessEntitlements ---");
string entitlementsRelative = ProcessEntitlements(path, proj, mainTarget, info, addHealthRecordsCapability);
#if UNITY_2019_3_OR_NEWER
// add HealthKit capability
Debug.Log("------projPath "+projPath);
ProjectCapabilityManager capabilities = new ProjectCapabilityManager(projPath, "Entitlements.entitlements", null, mainTarget);
capabilities.AddHealthKit();
Debug.Log("---BE:Capability UNITY_2019_3_OR_NEWER ---");
// add HealthKit Framework
//proj.AddFrameworkToProject(frameworkTarget, "HealthKit.framework", true);
// Set a custom link flag
//proj.AddBuildProperty(frameworkTarget, "OTHER_LDFLAGS", "-ObjC");
#else
// add HealthKit capability
Debug.Log("---ELSE BE:Capability UNITY_2019_3_OR_NEWER ---");
Debug.Log("projectPath:" + projPath);
Debug.Log("entitlementsRelative:" + entitlementsRelative);
Debug.Log("targetName:" + targetName);
ProjectCapabilityManager capabilities = new ProjectCapabilityManager(projPath, entitlementsRelative, targetName);
capabilities.AddHealthKit();
// add HealthKit Framework
proj.AddFrameworkToProject(mainTarget, "HealthKit.framework", true);
// Set a custom link flag
proj.AddBuildProperty(mainTarget, "OTHER_LDFLAGS", "-ObjC");
#endif
proj.WriteToFile(projPath);
}
}
// -------------------------------
internal static PlistDocument ProcessInfoPList(string path, bool addHealthRecordsCapability) {
string plistPath = Path.Combine(path, "Info.plist");
PlistDocument info = GetInfoPlist(plistPath);
PlistElementDict rootDict = info.root;
// // Add the keys
if (HealthKitBuildProcessor.shareString != null) {
rootDict.SetString("NSHealthShareUsageDescription", HealthKitBuildProcessor.shareString);
}
else {
Debug.LogError("unable to read NSHealthShareUsageDescription");
}
if (HealthKitBuildProcessor.updateString != null) {
rootDict.SetString("NSHealthUpdateUsageDescription", HealthKitBuildProcessor.updateString);
}
if (addHealthRecordsCapability) {
rootDict.SetString("NSHealthClinicalHealthRecordsShareUsageDescription", HealthKitBuildProcessor.clinicalString);
}
// Write the file
info.WriteToFile(plistPath);
return info;
}
internal static string ProcessEntitlements(string path, PBXProject proj, string target, PlistDocument info, bool addHealthRecordsCapability) {
string entitlementsFile;
string entitlementsRelative;
string entitlementsPath;
Debug.Log("PATH: " + path);
Debug.Log("TARGET: " + target);
String test= proj.GetUnityMainTargetGuid();
Debug.Log("TEST proj: " + test);
entitlementsRelative = proj.GetBuildPropertyForConfig(target, "CODE_SIGN_ENTITLEMENTS");
Debug.Log("entitlementsRelative: " + entitlementsRelative);
Debug.LogFormat("get build property [{0}, {1} = {2}]", target, "CODE_SIGN_ENTITLEMENTS", entitlementsRelative);
PlistDocument entitlements = new PlistDocument();
if (entitlementsRelative == null) {
string projectname = GetProjectName(info);
Debug.Log("projectname: " + projectname);
entitlementsFile = Path.ChangeExtension("Entitlements", "entitlements");
Debug.Log("entitlementsFile: " + entitlementsFile);
entitlementsRelative = Path.Combine(path, entitlementsFile);
Debug.Log("entitlementsRelative: " + entitlementsRelative);
entitlementsPath = Path.Combine(path, entitlementsRelative);
Debug.Log("entitlementsPath: " + entitlementsPath);
//proj.AddFileToBuild(target, proj.AddFile(entitlementsRelative, entitlementsRelative, PBXSourceTree.Source));
Debug.LogFormat("add build property [{0}, {1}] => {2}", target, "CODE_SIGN_ENTITLEMENTS", entitlementsRelative);
proj.AddBuildProperty(target, "CODE_SIGN_ENTITLEMENTS", entitlementsFile);
string newEntitlements = proj.GetBuildPropertyForConfig(target, "CODE_SIGN_ENTITLEMENTS");
Debug.Log("newEntitlements: " + newEntitlements);
Debug.LogFormat("=> {0}", newEntitlements);
}
else {
entitlementsPath = Path.Combine(path, entitlementsRelative);
Debug.Log("ELSE:entitlementsPath " + entitlementsPath);
}
ReadEntitlements(entitlements, entitlementsPath);
entitlements.root.SetBoolean("com.apple.developer.healthkit", true);
if (addHealthRecordsCapability) {
Debug.Log("addHealthRecordsCapability =TRUE ");
var healthkitAccess = entitlements.root.CreateArray("com.apple.developer.healthkit.access");
healthkitAccess.AddString("health-records");
}
SaveEntitlements(entitlements, entitlementsPath);
return entitlementsRelative;
}
// -------------------------------
internal static void ReadEntitlements(PlistDocument entitlements, string destinationPath) {
Debug.Log("READING Entitlements [ReadEntitlements]");
Debug.Log("READING from destinationPath [ReadEntitlements]"+ destinationPath);
if (System.IO.File.Exists(destinationPath)) {
try {
Debug.LogFormat("reading existing entitlements: '{0}'.", destinationPath);
entitlements.ReadFromFile(destinationPath);
}
catch (Exception e) {
Debug.LogErrorFormat("error reading from file: {0}", e);
}
}
}
internal static void SaveEntitlements(PlistDocument entitlements, string destinationPath) {
try {
Debug.Log("----SaveEntitlements---");
entitlements.WriteToFile(destinationPath);
}
catch (Exception e) {
Debug.LogErrorFormat("error writing to file: {0}", e);
}
}
internal static PlistDocument GetInfoPlist(string plistPath) {
// Get the plist file
PlistDocument plist = new PlistDocument();
plist.ReadFromFile(plistPath);
return plist;
}
internal static string GetProjectName(PlistDocument plist) {
string projectname = plist.root["CFBundleDisplayName"].AsString();
return projectname;
}
}
I don't know about Unity, but from Xcode when you add a capability for health kit it will update the entitlement file by itself

C# Can't access Properties.Resources

so, I am making a file binder.
saves1 and saves2 are the embedded resources and
I want to extract it in the temp folder.
Here's my code:
using System.IO;
using System.Diagnostics;
namespace _123
{
class Program
{
static void Main(string[] args)
{
string patdth = #"C:\Users\Alfred\AppData\Local\Temp";
byte[] lel1 = Properties.Resources.saves2;
byte[] lel = Properties.Resources.saves1;
File.WriteAllBytes(patdth + "\\hdhtehyr.exe", lel);
File.WriteAllBytes(patdth + "\\hdhdhdhgd.exe", lel1);
Process.Start(patdth + "\\hdhtehyr.exe");
Process.Start(patdth + "\\hdhdhdhgd.exe");
}
}
}
I get this error:
"Error CS0103 The name 'Properties' does not exist in the current
context ConsoleApplication3".
edit:
I am inserting the resources dynamically here, as you can see my code "/resources" + Path" is my way of adding the resources.
public void compile2(string file)
{
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters compars = new CompilerParameters();
compars.ReferencedAssemblies.Add("System.dll");
compars.ReferencedAssemblies.Add("System.Reflection.dll");
compars.ReferencedAssemblies.Add("System.IO.dll");
compars.GenerateExecutable = true;
compars.GenerateInMemory = false;
compars.TreatWarningsAsErrors = false;
compars.OutputAssembly = "Binded.exe";
compars.CompilerOptions = "/resources:" + textBox10.Text;
compars.CompilerOptions = "/resources:" + textBox11.Text;
compars.CompilerOptions = "/t:winexe";
if (string.IsNullOrWhiteSpace(textBox12.Text))
{
}
else
{
compars.CompilerOptions = "/win32icon:" + textBox12.Text;
}
CompilerResults res = provider.CompileAssemblyFromSource(compars, file);
{
MessageBox.Show("Code compiled!", "Success");
}
}
Under 'ConsoleApplication3' Project, double click 'Properties' -> Select 'Resources' tab -> Click on "This project does not contain a default resources file. Click here to create one." message. Add the files ('saves1' and 'saves2') here.

Check file exists and has the right naming standard in C#

We have a process from third-party vendor to drop sales and invetory data everyday and could have any of the following scenarios
Drop the right file. (Naming standard: test.xls)
Drop the right file but not follow the right naming standard. (Other
names could be test_mmddyyyy or testmmddyyyy)
No file dropped.
I am trying to build my logic around these scenarios and stuck at how to build my logic when the file exists but does not have the right naming standard and check for this condition and change the name of the file to the appropriate naming standard.
public void Main()
{
try
{
string filefullpathname = #"C:\Temp\test.xls";
if (File.Exists(filefullpathname) == false)
{
Console.WriteLine("File does not exist in the path");
}
// file exists but right naming standard not followed (Other names could be test_mmddyyyy or testmmddyyyy)
// how to check for this condition and change the name of the file to the naming standard
else
{
string dirname = #"C:\Temp\";
DirectoryInfo directory = new DirectoryInfo(dirname);
string filepartialname = "test";
FileInfo[] fileindirectory = directory.GetFiles(filepartialname + "*");
foreach (FileInfo filename in fileindirectory)
{
string fullname = filename.FullName;
bool ind = Path.HasExtension(fullname);
if (ind == false)
{
File.Move(fullname, directory + filepartialname + ".xls");
}
else
{
File.Move(fullname, directory + filepartialname + ".xls");
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception error)
{
Console.WriteLine(error);
}
}
It is not really clear as to if it is only the file name or a missing extension. So I put in both.
public void Main()
{
try
{
string dirname = #"C:\Temp\";
DirectoryInfo directory = new DirectoryInfo(dirname);
string filepartialname = "test";
FileInfo[] fileindirectory = directory.GetFiles(filepartialname + "*");
foreach (FileInfo filename in fileindirectory)
{
if (filename.Extension == "")
{
//doesn't have an extension
}
else if (!Regex.IsMatch(filename.Name.Replace(filename.Extension, ""), #"^[A-Z|a-z]$"))
{
//contains more then just test
}
else
{
//file is good
}
}
}
catch (Exception error)
{
Console.WriteLine(error);
}
}
Your explanation of what your inputs could be, and how you want to move those inputs isn't super clear, but this should get you started:
var expectedFilename = Path.Combine(someOtherDirectory, "test.xls");
// Matches test* and *.xls
var relevantFiles = Directory
.EnumerateFiles(searchDirectory, "*", SearchOption.TopDirectoryOnly)
.Where(f => Path.GetFileName(f).StartsWith("test") || Path.GetExtension(f).Equals(".xls"))
foreach (var file in relevantFiles)
{
// If there's more than one file matching the pattern, last one in wins
File.Move(file, expectedFilename);
}

Mimic Linux which command in C#

I use a tool's binaries in a C# project called GraphViz.
The problem is I must include the binaries path as hard-coded and I don't want to do that.
IRenderer renderer = new Renderer("C:\\Program Files (x86)\\Graphviz2.38\\bin"); // todo: remove hardcoded GraphViz path
I want to mimic the linux which command.
Simply passing the binary name (e.g dot) and get the path.
GetBinaryPath("dot"); // return the above path
I'd appreciate any ideas or topics to start searching.
Note
Target OS: Windows
.NET version : 4
If you need to find path given only executable name (and installation directory is in your PATH environment variable)
Option 1:
Using where command with Process class. (test for exit code, parse the output)
Option 2:
You can get environment PATH environment variable, split it by ';' and test for your executable name existence.
First you need to find all directories where windows search for a exectuable file and that is from the environment variable %PATH%.
Then you need to find all extensions (.com, .exe, .bat etc) from %PATHEXT%.
Then you just check them like this:
internal class Program {
private static void Main(string[] args) {
if (args.Length != 1) {
Console.WriteLine("Incorrect usage!");
return;
}
var extensions = GetExecutableExtensions(args[0]);
var paths = GetPaths();
var exeFile = GetFirstExecutableFile(args[0], extensions, paths);
if (exeFile == null) {
Console.WriteLine("No file found!");
}
else {
Console.WriteLine(exeFile);
}
}
private static string GetFirstExecutableFile(string file, string[] extensions, string[] paths) {
foreach (var path in paths) {
var filename = Path.Combine(path, file);
if (extensions.Length == 0) {
if (File.Exists(filename)) {
return filename;
}
}
else {
foreach (var ext in extensions) {
filename = Path.Combine(path, file + ext);
if (File.Exists(filename)) {
return filename;
}
}
}
}
return null;
}
private static string[] GetExecutableExtensions(string file) {
var data = GetCmdOutput("echo %PATHEXT%");
var arr = data.TrimEnd('\n', '\r').Split(new [] {';'}, StringSplitOptions.RemoveEmptyEntries);
//If the command passed in ends with a executable extension then we dont need to test all extensions so set it to emtpy array
foreach (var ext in arr) {
if (file.EndsWith(ext, StringComparison.OrdinalIgnoreCase)) {
return new string[0];
}
}
return arr;
}
private static string[] GetPaths() {
var data = GetCmdOutput("echo %PATH%");
return data.TrimEnd('\n', '\r').Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
private static string GetCmdOutput(string cmd) {
using (var proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "cmd.exe",
Arguments = "/c " + cmd,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
}) {
proc.Start();
return proc.StandardOutput.ReadToEnd();
}
}
}

An object reference is required for the nonstatic field, method, or property

Hi I am trying to writing a code which copy files from source folder to destination folder. If destination folder contains same file name then my program should store file with different name.
e.g.
Source Folder contains:
C:\test\
test1.txt
test2.txt
Destination folder contains
D:\test\
test1.txt
test2.txt
test3.txt
then copy action should copy test1.txt and test2.txt from source to destination folder with name changed to
test4.txt and test5.txt
This is not complete code. But I am getting error An Object reference is required for nonstatic field,method, or property. at getFileName( ref destfileName, ref targetPath).
Any help on this?
class Program
{
static void Main(string[] args)
{
string sourcefileName = null;
string destfileName = null;
string sourcePath = #"C:\test";
string targetPath = #"D:\test";
List<int> seqNum = new List<int>();
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
//File name is like text1.txt
sourcefileName = System.IO.Path.GetFileName(s);
if (System.IO.Directory.GetFiles(targetPath).Count() > 0)
{
foreach (string file in System.IO.Directory.GetFiles(targetPath))
{
if (file.Contains(sourcefileName))
{
int num;
string existingLatestFile = string.Empty;
destfileName = sourcefileName.Replace(".txt", string.Empty);
for (int i = 0; i < sourcefileName.Length; i++)
{
if (Char.IsDigit(sourcefileName[i]))
{
existingLatestFile += sourcefileName[i];
}
}
if (int.TryParse(existingLatestFile, out num))
{
seqNum.Add(num);
}
destfileName = destfileName.Replace(existingLatestFile, string.Empty);//Remove existing number
num = num + 1;
destfileName = destfileName + num.ToString() + ".txt"; // Make a new file name
while (!getFileName( ref destfileName, ref targetPath))
{
}
}
else
{
destfileName = sourcefileName;
}
string destFile = System.IO.Path.Combine(targetPath, destfileName);
System.IO.File.Copy(s, destFile, false);
}
}
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
if (System.IO.Directory.GetFiles(targetPath).Count() > 0)
{
foreach (string file in System.IO.Directory.GetFiles(targetPath))
{
/* if (file.Contains(dir + "\\" + filename))
{
int num;
existingLatestFile = file.Replace(dir + "\\" + filename, string.Empty);
existingLatestFile = existingLatestFile.Replace(".txt", string.Empty);
if (int.TryParse(existingLatestFile, out num))
{
seqNum.Add(num);
}
}*/
Console.WriteLine(file);
}
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
bool getFileName(ref string filename, ref string destFolder)
{
bool retValue =false;
foreach (string file in System.IO.Directory.GetFiles(destFolder))
{
if (file.Contains(filename))
{
retValue = false;
}
else
{
retValue = true;
}
}
return retValue;
}
}
Main() is a static method.
It is not associated with any instance.
You need to make the other method static as well.
main is a static method, to call the non-static method getFileName you need to create a instance first
change
while (!getFileName...
to
Program p = new Program();
while (!p.getFileName...

Categories

Resources