This is just a sample, but it will help illustrate what I'm trying to do.
I know how to get the current directory as shown in the script below, and I can can set a file variable.
The problem I'm having is that I can't figure out how to make it create a folder and put the file in the folder
For example (using the variables below)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd: \5app\);
File.Copy(c:\xyz.txt, cd: \5app\xyz.txt
}
}
}
I know what I have written above is not correct because vs10 tells me so, but doesn't give me very much help.
You're missing a parenthesis and a semicolon, and, especially, arguments of methods Directory.CreateDirectory() and File.Copy() are strings, put them inside quotes:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd + #"\5app\");
File.Copy(#"c:\xyz.txt", cd + #"\5app\xyz.txt");
}
}
}
MSDN references: Directory.CreateDirectory, File.Copy
Thanks to Cole Johnson for pointing out that it shouldn't be #"cd: \5app\".
You don't use quotes.
In addition, I recommend against explicit parameter naming. If you look at the CIL generated when using explicit parameters, there is a performance downgrade as the parameter variables are saved to a local variable, then passed. This results in an unneeded strfld command.
There are several problems with your code, which Compiler Errors will likely help you to unravel:
The method Directory.CreateDirectory(string path) requires a string, which is encased in "".
Here is an MSDN article on how to use Directory.CreateDirectory
Same with the method File.Copy(string source, string destination)
Here is an MSDN article on how to use File.Copy
Since Directory.GetDirectory() returns a string, you can just concatinate your specific directory to the result. But remember to use proper Escape Sequences in your strings for things like Backslash.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd + "\\5app\\");
File.Copy("c:\\xyz.txt", cd + "\\5app\\xyz.txt");
}
}
}
Related
Development Environment: .Net Framework 4.7.2 using VS 2022 on Win 10 Pro x64
Preface: I've reviewed the two similar questions I found at SO; the first deals with permissions and the second with restrictions on using the root directory. Neither contained info that enabled me to resolve my issue.
I'm working on a C# winforms app which uses a SQLite database. I recently discovered "PRAGMA integrity_check" will create an empty DB and return “ok” if the target DB file is missing so I need to ensure the file’s not gone missing before executing the PRAGMA. My simple solution is to wrap integrity_check in an IF (File.Exist) ELSE but the Exist method is returning ”false”.
In MSDN documentation there 7 stated reasons why a false might be returned in addition to the file actually not existing (listed to avoid the need to follow a link):
path is null
path is invalid
path exceeds maximum length (260)
path is a zero-length string
path has invalid characters
storage media is failing/missing
caller has insufficient permissions to read the specified file
My operating assumption is none of those are the root cause since I can read from and write to the DB programmatically in the app.
Code building the path:
namespace BURS_Library
{
public class MISC
{
public const string DBName = "BURS.db";
}
}
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace BURS_Library
{
public class BURS_Path
{
public static string AppData()
{
string userAppDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
userAppDataDir = userAppDataDir.Replace("Roaming", "LocalLow");
if ( ! Directory.Exists(Path.Combine(userAppDataDir, "BURS_Data_tst")))
{
// display error MessageBox
Environment.Exit(1);
}
return Path.Combine(userAppDataDir, "BURS_Data_tst");
}
public static string DB()
{
return Path.Combine(AppData(), MISC.DBName);
}
{
}
Resultant path: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
Code with File.Exist
using _Library;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace BURS_UI
{
public static class Program
{
[STAThread]
public static void Main(string[] tsArgs)
{
if (File.Exists(BURS_Path.DB()))
{
// perform db Integrity Check
}
else
{
// display error MessageBox
Environment.Exit(2);
}
BURS_Connections.SetConnection(BURS_Path.DB());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Discover());
}
}
}
If my operating assumption is valid why is File.Exist returning false?
Thank you for your time & expertise.
Following #BentTranberg's suggestion a test was run using the following code (in case its useful to somebody):
if (Directory.Exists(#"C:\Users"))
Save2Log(#"FOUND: C:\Users", true);
if (Directory.Exists(#"C:\Users\Art"))
Save2Log(#"FOUND: C:\Users\Art", true);
if (Directory.Exists(#"C:\Users\Art\AppData"))
Save2Log(#"FOUND: C:\Users\Art\AppData", true);
if (Directory.Exists(#"C:\Users\Art\AppData\LocalLow"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow", true);
if (Directory.Exists(#"C:\Users\Art\AppData\LocalLow\BURS_Data_tst"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst", true);
if (File.Exists(#"C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db", true);
Save2Log($"METHOD: {BURS_Path.DB()}", true);
Which produced the following result:
FOUND: C:\Users
FOUND: C:\Users\Art
FOUND: C:\Users\Art\AppData
FOUND: C:\Users\Art\AppData\LocalLow
FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst
FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
METHOD: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
Next I reran my original code which surprisingly now worked as expected. To validate that result I ran more test:
int existFail = 0;
for (int i = 0; i < 10000; i++)
{
if ( ! File.Exists(BURS_Path.DB())) existFail++;
}
Save2Log($"number of exist fail in 10,000 = {existFail}", true);
I did that 5 times and in 50,000 iterations there were zero incorrect returns. At this point the error has not been reproduced.
My computer was shut down over night which may have impacted the findings. I will rerun this each morning for the next 3 days and post the results as an edit.
Below is my code to create a directory in my PC.
using System;
using System.IO;
using System.Text;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dataDir = new DirectoryInfo(#"C:\CsharpData");
Console.WriteLine(dataDir.Attributes);
Console.ReadLine();
}
}
}
But, the result looks like this.
Attribute is equal to -1, and I can't get my desired directory.
Can anyone let me know what my mistake is?
Use below code. You need to use create ,ethod for creating the directory.
DirectoryInfo dataDir = new DirectoryInfo(#"C:\CsharpData");
if(!dataDir.Exists)
{
dataDir.Create();
}
System.Console.WriteLine(dataDir.Attributes);
System.Console.ReadLine();
I have a litle program in c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int count;
static void Main(string[] args)
{
for (int i = 0; i<10; i++)
{
Console.WriteLine(func_count());
Console.ReadKey();
}
}
static int func_count()
{
return count++;
}
}
}
I want to write another simple C# program that will be able JUST to execute the func_count(). The first exe will be allready running, I don't want to execute it inside the second application and reflect it's properties.
In C after getting the right to access the memory region to avoid seg fault I would have to use a pointer to a function - something like:
int (* func_ptr)(); //pointer to function
func_ptr = func_count_address
What's a simple way to do this in C# like above?
Suppose that the first program (the one given) is as is and I can't change the code.
Thank you
Why not simply call the static method: ConsoleApplication1.Program.func_count(). This of course assumes that you reference the assembly where ConsoleApplication is located within your second app and that the method you want to invoke is public (which is currently is NOT).
EDIT: If you may not change the access-modifier of the desired method you may use reflection to invoke it however.
Sth. like this:
MethodInfo m = typeof(ConsoleApplication.Program).GetMethod("func_count", BindingFlags.NonPublic);
object result = m.Invoke(null, yourParams);
Usually you´d need an instance on which that method is executed. Since your method is static it does not need it and therefor the first param to Invoke is NULL.
after along time of searching via google, I decided to poste my problem here.
First: I am total C# Noob. I am using a Macro Recorder from Jitbit and I have no choice to use a different. The Problem is in the Macro Recorder, it is missing some essential things.
Like reading a text file into a variable and paste this variable via Clipboard :-(
However the good thing is, the tool support "some" type of native C# Code
If I open the C# Command I get this:
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
And the C# program has to follow also these rules:
=> This Code MUST contain a class named "Program" with a static method "Main"
I already used google and found code that should do the job but I get errors, I guess the
code doesn`t follow the above rules.
This is what I found and tried:
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("Counter.txt");
string counter = myFile.ReadToEnd();
myFile.Close();
// Load string into clipboard
Clipboard.SetDataObject( counter, true );
}
}
I always get the error : "Line 15: The Name Clipboard is not existing in the context"?!?
I hope that someone can explain a noob (me) what is wrong and what is the correct code.
Thanks.
add reference to System.Windows.Forms
using System;
using System.IO;
using System.Windows.Forms;
public class Program
{
[STAThread]
public static void Main()
{
Clipboard.SetDataObject(File.ReadAllText("Counter.txt"), true);
}
}
Note that to Avoid the ThreadStateException you need to applying the STAThread attribute to your Main() function
I think I found a bug. In my opinion Process.Start runs wrong directory.
To test, create default console application template and paste following:
using System;
using System.Diagnostics;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool test = false;
DirectoryInfo root = Directory.CreateDirectory(
System.IO.Path.Combine(Directory.GetCurrentDirectory(), "folder"));
DirectoryInfo bug = Directory.CreateDirectory(
System.IO.Path.Combine(root.FullName, "bug"));
DirectoryInfo bugDotCom = Directory.CreateDirectory(
System.IO.Path.Combine(root.FullName, "bug.com"));
ProcessStartInfo bugPSI = new ProcessStartInfo(bug.FullName);
ProcessStartInfo bugDotComPSI = new ProcessStartInfo(bugDotCom.FullName);
if (test)
{
Console.WriteLine(bug.FullName);
Process.Start(bugPSI);
}
else
{
Console.WriteLine(bugDotCom.FullName);
Process.Start(bugDotComPSI);
}
Console.ReadKey();
}
}
}
when variable test is set to false, bug.com directory should be opened, otherwise bug directory. However, this example shows that always bug.com is opened (no matter to test variable) - at least for me.
What's wrong? I'm missing something or that's just a bug?
.com is part of %PATHEXT%, so Windows will use it if it exists.
Changing the extension so that there is no bug.com folder avoids the problem.
To fix the problem, add a \ to the end of the path.