Where to find "InOut\\" path in csharp? - c#

I have a charp file and have created in JetBrainsRider -> Console Project.
In main method, there is code as below
static void Main(string[] args)
{
string FileNamePrefix = string.Empty;
string InfoFileName = string.Empty;
if (args.Count() > 0)
{
FileNamePrefix = args[0];
}
else
{
Console.Write("Enter File Name (no extension): ");
FileNamePrefix = Console.ReadLine();
}
InfoFileName = "InOut\\" + FileNamePrefix + "-INFO.TXT";
if (!File.Exists(InfoFileName))
{
Console.WriteLine("{0} does not exist. Run Terminated", InfoFileName);
return;
}
}
When I place a TestInput-INFO.TXT file in project folder and give name in readline input, it gives error:
Enter File Name (no extension): TestInput
InOut\TestInput-INFO.TXT does not exist. Run Terminated
Where should I put my input file?

It is relative to the current directory — see Environment.CurrentDirectory.
When executing a program from within the IDE, the exe file is located in the bin folder, and hence that is the current directory for the process.

Related

OpenWith Application

Is there any way to detect when a file is opened with a c# application
Example
When I right-click on a file then select to open it with My Application I want this code to run
File.WriteLines(OpenWithFile)
Is this achievable
Yes, it's achievable. When a user clicks Open With in Windows Explorer, the operating system includes the filename as the first argument. Below is a demo how you'd get the file name that the user clicked to open with your application. You can than implement whatever processing you wish.
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
var OpenWithFile = args[0];
Console.WriteLine($"The OpenWithFile is: {OpenWithFile}");
}
else
{
Console.WriteLine("No command-line arguments were passed.");
}
Console.WriteLine("Press any key to continue.");
Console.ReadLine();
}
}

Writing a report of cpp file in txt format with same name as file name

I am reading files from a directory and reading all text and generating reports separately for each file. I want report name same as file name.
I have tried to get file name but when I pass it to reporting module it gives exception error.
string path = "D:\\AssertCount\\";
foreach (string sFile in Directory.EnumerateFiles(path))
{
assertCount=0;
reportingCounter++;
string[] files = Directory.GetFiles(path);
string fileName = files[reportingCounter];
}
ReportWriting(totalWords, assertCount,fileName);
here is complete report writing module
public static void ReportWriting(int totalWords, int assertCount,string fileName)
{
StreamWriter file = new StreamWriter("D:\\AssertCount\\Reports\\"+fileName+".txt");
file.Write("TotalWords = " + totalWords);
file.Write("\nAasserts = " + assertCount);
file.Write("\nOccurence of assert keyword in code is " + assertPercentage + " % ");
file.Close();
}
followin exception occurs
System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect : 'D:\AssertCount\Reports\D:\AssertCount\testData2.cpp.txt''
The issue is that Directory.EnumerateFiles() and Directory.GetFiles() return full paths, not file names. You could try replacing
string fileName = files[reportingCounter];
with
string fileName = Path.GetFileNameWithoutExtension(files[reportingCounter]);
to turn the full path into just the file name, without the extension (since you add on ".txt" later).
Alternatively, you're already enumerating the files in the directory with the foreach, so why not just use sFile?
foreach (string sFile in Directory.EnumerateFiles(path))
{
assertCount=0;
string fileName = Path.GetFileNameWithoutExtension(sFile);
ReportWriting(totalWords, assertCount,fileName);
}
You're duplicating the path:
'D:\AssertCount\Reports\D:\AssertCount\testData2.cpp.txt' (It should be just 'D:\AssertCount\testData2.cpp.txt'
The variable fileName already includes the full path to the resource (not only the file name). So you could just delete "D:\AssertCount\Reports\" from the creation of the StreamWriter object. The code would be like this
public static void ReportWriting(int totalWords, int assertCount,string fileName)
{
StreamWriter file = new StreamWriter(fileName+".txt");
file.Write("TotalWords = " + totalWords);
file.Write("\nAasserts = " + assertCount);
file.Write("\nOccurence of assert keyword in code is " + assertPercentage + " % ");
file.Close();
}

Application: Application Launcher, can't Move directory, it's being used by another process

I'm writing application launcher as a Window Application in C#, VS 2017. Currently, having problem with this piece of code:
if (System.IO.Directory.Exists(extractPath))
{
string[] files = System.IO.Directory.GetFiles(extractPath);
string[] dirs = Directory.GetDirectories(extractPath);
// 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.
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.File.Move(s, destFile);
}
foreach (string dir in dirs)
{
//var dirSplit = dir.Split('\\');
//var last = dirSplit.Last();
//if (last != "Resources")
//{
var fileName = System.IO.Path.GetFileName(dir);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.Directory.Move(dir, destFile);
//}
}
}
I'm getting well known error
"The process cannot access the file 'XXX' because it is being used by another process."
I was looking for solution to fix it, found several on MSDN and StackOvervflow, but my problem is quite specific. I cannot move only 1 directory to another, which is Resources folder of my main application:
Here is my explanation why problem is specific:
I'm not having any issues with moving other files from parent directory. Error occurs only when loop reaches /Resources directory.
At first, I was thinking that it's beeing used by VS instantion, in which I've had main app opened. Nothing have changed after closing VS and killing process.
I've copied and moved whole project to another directory. Never opened it in VS nor started via *.exe file, to make sure that none of files in new, copied directory, is used by any process.
Finally, I've restarted PC.
I know that this error is pretty common when you try to Del/Move files, but in my case, I'm sure that it's being used only by my launcher app. Here is a little longer sample code to show what files operation I'm actually doing:
private void RozpakujRepo()
{
string oldPath = #"path\Debug Kopia\Old";
string extractPath = #"path\Debug Kopia";
var tempPath = #"path\ZipRepo\RexTempRepo.zip";
if (System.IO.File.Exists(tempPath) == true)
{
System.IO.File.Delete(tempPath);
}
System.IO.Compression.ZipFile.CreateFromDirectory(extractPath, tempPath);
if (System.IO.Directory.Exists(oldPath))
{
DeleteDirectory(oldPath);
}
if (!System.IO.Directory.Exists(oldPath))
{
System.IO.Directory.CreateDirectory(oldPath);
}
if (System.IO.Directory.Exists(extractPath))
{
string[] files = System.IO.Directory.GetFiles(extractPath);
string[] dirs = Directory.GetDirectories(extractPath);
// 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.
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.File.Move(s, destFile);
}
foreach (string dir in dirs)
{
//var dirSplit = dir.Split('\\');
//var last = dirSplit.Last();
//if (last != "Resources")
//{
var fileName = System.IO.Path.GetFileName(dir);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.Directory.Move(dir, destFile);
//}
}
}
string zipPath = #"path\ZipRepo\RexRepo.zip";
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
And now, my questions:
Can it be related to file types (.png, .ico, .bmp) ?
Can it be related to fact, that those resources files are being used like, as, for example .exe file icon in my main application? Or just because those are resources files?
Is there anything else what I'm missing and what can cause the error?
EDIT:
To clarify:
There are 2 apps:
Main Application
Launcher Application (to launch Main Application)
And Resources folder is Main Application/Resources, I'm moving it while I'm doing application version update.
It appeared that problem is in different place than in /Resources directory. Actually problem was with /Old directory, because it caused inifinite recurrence.

Whats the code to create a directory if it doesnt exist?

I am having a problem with coding my save-directory. I want it to create a folder called "Ausgabe" (Output) on the current users Desktop, but I do not know how to check if it already exists and if it doesn't then create it.
This is my current code for that part so far:
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// need some code here
}
What do I add in order to make it do what I want it to do?
You can check if a directory exists using
Directory.Exists(pathToDirectory)
and create a directory using
Directory.CreateDirectory(pathToDirectory)
EDIT In response to your comment:
string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Ausgabe")
should give you the path to a folder named 'Ausgabe' in the users Desktop-folder.
Just use Directory.CreateDirectory. If the directory exists the method will not create it (in other words it contains a call to Directory.Exists internally)
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
public Form1()
{
string myFolder = Path.Combine(path, "Ausgabe");
Directory.CreateDirectory(myFolder);
}
To use this method you need to add a using System.IO to the top of your Form1.cs file.
I wish also to say that the Desktop is not the most appropriate place to create a directory for your application. There is a proper place provided by the System and it is under the ProgramData enum (CommonApplicationData or ApplicationData)
string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
As per this doc, the Directory.CreateDirectory Method (String) will
Creates all directories and subdirectories in the specified path
unless they already exist.
So it is fine to use like this:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string desktopFolder = Path.Combine(path, "New Folder");
Directory.CreateDirectory(desktopFolder);
You can use the Directory.Exists() method: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
Your code would propebly look something like this:
public static void Main()
{
// Specify the directory you want to manipulate.
string path = #"c:\MyDir";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
I have had a recent issue so here is my solution,
I had to find the deployed directory
var deployedDir = Assembly.GetEntryAssembly().CodeBase;
deployedDir = Path.GetDirectoryName(deployedDir);
deployedDir = deployedDir.Replace("file:\\", "");
var pathToDirectory= Path.Combine(deployedDir, "YourFileName");
Then do what the above answers show and create the directory if it doesnt exist,
Directory.CreateDirectory(pathToDirectory)

Getting an index outside bound of an array in C#

This program is supposed to show the path of a directory and the directory if its exists then it should also show the files inside with the following extensions (i.e .doc, .pdf, .jpg, .jpeg) but I'm getting an error
*Index was outside the bounds of the array.
on this line of code
string directoryPath = args[0];
This is the code in the main function
class Program
{
static void Main(string[] args)
{
string directoryPath = args[0];
string[] filesList, filesListTmp;
IFileOperation[] opList = { new FileProcNameAfter10(),
new FileProcEnc(),
new FileProcByExt("jpeg"),
new FileProcByExt("jpg"),
new FileProcByExt("doc"),
new FileProcByExt("pdf"),
new FileProcByExt("djvu")
};
if (Directory.Exists(directoryPath))
{
filesList = Directory.GetFiles(directoryPath);
while (true)
{
Thread.Sleep(500);
filesListTmp = Directory.GetFiles(directoryPath);
foreach (var elem in Enumerable.Except<string>(filesListTmp, filesList))
{
Console.WriteLine(elem);
foreach (var op in opList)
{
if (op.Accept(elem)) op.Process(elem);
}
}
filesList = filesListTmp;
if (Console.KeyAvailable == true && Console.ReadKey(true).Key == ConsoleKey.Escape) break;
}
}
else
{
Console.WriteLine("There is no such directory.");
}
}
}
How can I handle this error it seems to be common but it happens id different ways
You need to pass the necessary arguments to the program when running it. You can either do this by running the program from the command line, or else when running Visual Studio by doing the following:
Right click on project
Properties
Debug tag
Enter arguments under Start Options -> Command line arguments
You might want to pass the arguments into the program from command line.
like this:
> yourProgram.exe directoryName
Also, to avoid such problems in the code,
if(args.Length > 0){
string directoryPath = args[0];
}else{
//print a help message and exit, or do something like set the
//default directoryPath to current directory
}
Do you want the user to enter a path when the program starts or when they start the program? If it's the first, then you should add a Console.Read() method that asks for the path.
If it's the latter, then you need to pass the path as an argument when starting the program. You should also do a check against the args array before reading from it to check that it contains data and that data is a valid path.
Something like:
if(args.Length > 0 && Directory.Exists(args[0]))
{
// Do Something.
}

Categories