I'm new to coding - so bear with me. I've done a lot of reading and can't figure this one out.
So when you run my new the app, you type in a folder name. The app goes to that folder, then will scan through 2 different log files that are in this designated folder. BUT here is where I'm getting in trouble. If the log does NOT exist - it will ask if you want to create the file that it is looking for... I do NOT want it to do that. I would just like it to go to the folder, if the file does not exist then do nothing and move on to the next line of code.
Here is the code I have so far:
private void btnGo_Click(object sender, EventArgs e)
{
//get node id from user and build path to logs
string nodeID = txtNodeID.Text;
string serverPath = #"\\Jhexas02.phiext.com\rwdata\node\";
string fullPath = serverPath + nodeID;
string dbtoolPath = fullPath + "\\DBTool_2013.log";
string msgErrorPath = fullPath + "\\MsgError.log";
//check if logs exist
if (File.Exists(dbtoolPath) == true)
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
The app will display The 2013 DBTool log does not exist for this Node. - then it opens Notepad and asks me if it wants to create the file.
Cannot find the \\Jhexas02.phiext.com\rwdata\node\R2379495\DBTool_2013.log file.
Do you want to create a new file?
I DO NOT want to create a new file, ever. Any good ways to get around this?
You skipped "Else" after "if"
if (File.Exists(dbtoolPath) == true)
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
else
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
While your code compiles (it's valid to just add bracers like that) it could be as simple as adding else to your if statement:
if (File.Exists(dbtoolPath) == true) // This line could be changed to: if (File.Exists(dbtoolPath))
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
else // Add this line.
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
As your code looks now, this part will always run:
{
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
It's essentially the same as this code:
if (File.Exists(dbtoolPath) == true)
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
try this :
if (File.Exists(dbtoolPath))
{
System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
else {
MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}
Related
I have Three strings that are set to the current: year, month, day respectively using the "DateTimeNow". and I have set a path to a string of the root folder named "Custom_project" by grabbing the file path from a text file on the desktop.
They are named:
public string CurrentYear;
public string CurrentMonth;
public string CurrentDay;
public string CustomOrderFilePathTopFolder = File.ReadAllText("C:/desktop/Custom_project.txt");
//CustomOrderFilePathTopFolder now ='s C:/desktop/Custom_project/
Okay so I am trying to check to see if a folder exists(Folder Named: "CurrentYear" or in this case "2020" inside of the: "Custom_project" folder) and if not then create the folder with the string, if it does exist then it will then proceed to my next step which is essentially opening the file: "CurrentYear" or "2020, then repeating the same thing but inside of that folder: Custom_project/2020, for month and repeat one last time for day.
So In the end I would have a file path that looks like so: "C:/desktop/Custom_project/2020/07/12".
Now To My Question:
"HOW DO I GO ABOUT CHECKING IF A FILE NAMED "2020" EXISTS INSIDE OF THE CUSTOMPATHFOLDER AND IF IT DOESN'T THEN CREATE THAT FOLDER
I just tried using This(Which doesn't seem to work):
if (CustomOrderFilePathTopFolder == "")
{
MessageBox.Show("ERROR FILE PATH CANNOT BE EMPTY!");
}
else if (!Directory.Exists(CustomOrderFilePathTopFolder + CurrentYear))
{
Directory.CreateDirectory(CustomOrderFilePathTopFolder + CurrentYear);
}
This Does nothing for me so I tried this:
if (CustomOrderFilePathTopFolder == "")
{
MessageBox.Show("ERROR FILE PATH CANNOT BE EMPTY!");
}
else if (!Directory.Exists(CustomOrderFilePathTopFolder + "/" + CurrentYear))
{
Directory.CreateDirectory(CustomOrderFilePathTopFolder + "/" + CurrentYear);
}
Doesn't Work Either So I am At a loss Please Let me know how I would go about this please and thank you a ton!!
Try below steps
you need to first combine path to point proper file/folder
Check File exists or not
If not, then create folder with same name.
using System.IO;
...
var filePath = Path.Combine(CustomOrderFilePathTopFolder, CurrentYear))
if (!File.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
EDIT:
My problem has been solved thanks to the user Chris Larabell, thank you to all that responded.
The issue that is happening with my code is that when the said file is not present in the Desktop directory, the console will close and will not go to the else statement for what happens when the file is not present. When the file is present however, the console will work completely fine, it is just the else statement.
Here is my code that is being used.
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = #"delete.txt";
string[] fileList = System.IO.Directory.GetFiles(Desktop, DeleteFile);
foreach (string file in fileList)
{
if (System.IO.File.Exists(file))
{
System.IO.File.Delete(file);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("search has encountered an error");
Console.ReadLine();
}
}
What I am trying to accomplish is to find a file through the Desktop directory with the name of 'delete.txt' and to delete it when the user enters "search.system". the console would then say back to you that the file has been deleted. If the file has not been found, it would say that "the file could not be found" back to you through console. If an error would to occur, it would go to catch and say "search has encountered an error"
I also want to say that I am sorry if this code is messy and/or if this is completely wrong from what I am trying to accomplish. I am new to C#, and new to coding in general.
You would want to put an if statement to check that the fileList length is > 0. If the file length is zero, the file was not found. Otherwise, you can proceed to delete the file.
Also, don’t be discouraged as a new coder. Set a breakpoint at the line where you use the GetFiles() method and step (F11) to the next line. Hover your cursor over the fileList variable and see if the number of items in the array is zero.
System.IO.Directory.GetFiles()
It looks like you are simply looking for a specific file by name and deleting it if it exists. You could simplify your code by doing this:
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = #"delete.txt";
string filePath = System.IO.Path.Combine(Desktop, DeleteFile);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
catch (System.Exception ex)
{
Console.WriteLine($"search has encountered an error: {ex}");
Console.ReadLine();
}
}
I want ask an easy question about my code in c# .... I know that there are lot of topics with same or similar topic/code result. But I need to hand in my code to school, so I can't just use the best solution on Stackoverflow or another page. I showed my code to my teacher and now need to fix a little bug.
The Code is about backing up files with a console report, so in first step I check if a folder exists. Second step is to report that the folder exists or doesn't exist, if it doesn't the code creates this folder and rechecks ...
SITUATION : CONSOLE REPORT
folders doesnt exist:
02:02:06 directory for backup Exist ... can continue
02:02:05 directory for backup DOESNT EXIST ... creating required folders...
folders exist :
02:02:55 directory for backup Exist ... can continue
02:02:54 directory for backup Exist ... can continue
In the 1st example the report is OK, but in the 2nd, my code tells me the same information twice... i just can't get my code to work properly..
Here is my code:
public void checkbackupfolders() {
do {
create_backup_folders();
} while (create_backup_folders() == false);
}
public bool create_backup_folders()
{
string path = "\\BACKUP\\" + Globals.hostname;
if (Directory.Exists(path))
{
consolecho("directory for backup Exist ... can continue");
return true;
}
else
{
consolecho("directory for backup DOESNT EXIST ... creating required folders...");
Directory.CreateDirectory("\\BACKUP\\" + Globals.hostname);
return false;
}
}
Why are you calling the method twice here?:
do {
create_backup_folders();
} while (create_backup_folders() == false);
That's going to make things confusing, as you're now discovering. Just call the method once on each loop iteration and store the result of the method. Then use that stored result in the loop condition:
var canContinue = false;
do {
canContinue = create_backup_folders();
} while (canContinue == false);
Okay, so me and several others are trying to move a bunch of files from a game launcher. To said directory of your choice.
The problem is, the files wont move.
The way the launcher works, is you click install on the game, it installs a bunch of files to the location of your choice. But the files wont move.
Here' the code.
private void MoveFolders()
{
string sourceDir = Config.GetGamePath();
string destinationDir = textBoxFolder.Text;
try
{
if (Directory.Exists(sourceDir) == true)
{
if (bGameIsInstalled == true && textBoxFolder.TextLength > 0)
{
Directory.Move(sourceDir, destinationDir);
bMoveFolders = true;
}
else
{
MessageBox.Show("Select Arma 3 directory before starting game");
}
}
else
{
// Do somthing about source directory not existing -
}
}
catch (Exception ex)
{
//TODO: Handle the execption that has been thrown will do this on launcher update
}
}
You can use CopyFile. As you said this should be a installer, i wouldn't move them folders to another direction. Just copy it, because you can't use the installer one more time after all these files needed are moved away.
And if you debug it, please just don't use try and catch. Test your code simply.
I am trying to do a check on the isolated storage followed by some command along with it.
What i wanted was to check for directories name consisting "a*"
*If the directories exist* it will check if the diretory named after "a + today date" exist.
If it exist will show up a pop up message telling it does exist.
But if no directories consisting of "a*" is exist at all it will show a message of "Does not exist".
Below is my code:
Is able to check if the directories exist when there is a directory of "a*" is created.
But it does not work *when none of the directories "a" is created**.
How should i modify my code?
Code:
string[] fileNames;
string selectedFolderName;
private void gameBtn_Click(object sender, RoutedEventArgs e)
{
//MediaPlayer.Stop();
string currentDate = DateTime.Now.ToString("MMddyyyy");
string currentDateName = "a" + currentDate;
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
fileNames = myStore.GetDirectoryNames("a*");
foreach (var name in fileNames)
{
if (fileNames.Contains(currentDateName))
{
selectedFolderName = currentDateName;
MessageBox.Show("Your schedule for today");
NavigationService.Navigate(new Uri("/DisplaySchedule.xaml?selectedFolderName=" + selectedFolderName, UriKind.Relative));
}
else
{
MessageBox.Show("No Schdule for today", "Schedule Reminder", MessageBoxButton.OK);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
}
}
Your error is just a simple typo.
if (fileNames.Contains(currentDateName))
should be
if (name.Contains(currentDateName))
As for handling when there's no directory "a*", check if fileNames is empty.
if (fileNames.Length == 0) // no Directory 'a' was found, create it
{
// create code here
}