Moving a folder, from one directory to another. in c# - c#

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.

Related

C# else statement not run when file not found

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();
}
}

c# check->create->check folder loop

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);

Check if folder contains files with certain extensions

I have other C# code that drops a call recording file into the folder c:\Recordings
Each file has the extension of .wma
I'd like to be able to check the folder every 5 minutes. If the folder contains a file ending in .wma i'd like to execute some code.
If the folder does not contain a file with the .wma extension, i'd like the code to pause for 5 minutes and then re-check (infinitely).
i've started with the following the check if the folder has any files in it at all, but when I run it, it always reports the folder contains files, even though it does not.
string dirPath = #"c:\recordings\";
if (Directory.GetFiles(dirPath).Length == 0)
{
NewRecordingExists = true;
Console.WriteLine("New Recording exists");
}
else
{
NewRecordingExists = false;
Console.WriteLine("No New Recording exists");
System.Threading.Thread.Sleep(300000);
}
if (Directory.GetFiles(dirPath).Length == 0)
This is checking if there are no files... then you are reporting "New Recording exists". I think you just have your logic the wrong way around. else is where it means you have found some files.
In addition, if you want to check for just *.wma files then you can use the GetFiles overload that takes a search pattern parameter, for example:
if (Directory.GetFiles(dirPath, "*.wma").Length == 0)
{
//NO matching *.wma files
}
else
{
//has matching *.wma files
}
SIDE NOTE: You may be interested in the FileSystemWatcher, this would enable you to monitor your recordings folder for changes (including when files are added). This would eliminate your requirement to poll every 5 minutes, and you get near-instant execution when the file is added, as opposed to waiting for the 5 minute interval to tick over
First of all your logic is reversed! ;)
here is you correct code:
bool NewRecordingExists;
string dirPath = #"c:\recordings\";
string[] fileNames = Directory.GetFiles(dirPath, "*.wma", SearchOption.TopDirectoryOnly);
if (fileNames.Length != 0)
{
NewRecordingExists = true;
foreach (string fileName in fileNames)
{
Console.WriteLine("New Recording exists: {0}", fileName);
/* do you process for each file here */
}
}
else
{
NewRecordingExists = false;
Console.WriteLine("No New Recording exists");
System.Threading.Thread.Sleep(300000);
}
Although, i recommend using System.Timers.Timer class for you application!
Don't use GetFiles if you're going to throw the result away.
Use an enumeration so you can exit early:
Directory.EnumerateFiles(Folder, "*.wma", SearchOption.AllDirectories).FirstOrDefault() != null

Relog can't open a binary log file if executed from C#

I've written a simple windows service to watch a folder and run relog (the windows tool to export data from binary perf mon files) on any files that arrive.
When I run it from my c# process (using System.Diagnostics.Process.Start()) I get:
Error:
Unable to open the specified log file.
But if I copy and paste the command into a console window it works fine.
I've looked all over the net but everything seems to point to a corrupt file, which I know is not the case as I can import perfectly when running manually.
Any help greatly appreciated.
If you are using FileSystemWatcher to monitor for files it will fire the created event before the file is completely written to disk, this would cause the kind of error from relog about being unable to "open" a file since it might still be locked and technically corrupt as far as it's concerned.
I've written the following helper method that I always use in conjunction with FileSystemWatcher to wait for a file to be completely written and ready for processing after a created event and will also kick out after a timeout:
public static bool WaitForFileLock(string path, int timeInSeconds)
{
bool fileReady = false;
int num = 0;
while (!fileReady)
{
if (!File.Exists(path))
{
return false;
}
try
{
using (File.OpenRead(path))
{
fileReady = true;
}
}
catch (Exception)
{
num++;
if (num >= timeInSeconds)
{
fileReady = false;
}
else
{
Thread.Sleep(1000);
}
}
}
return fileReady;
}

How did this application update itself?

i have been looking for a way to update my application for ages, and still haven't found a solution. (Please don't say ClickOnce, it isn't suitable for this app).
Years ago i used to use MCadmin to run a Minecraft server, and i remembered that when it started, sometimes it would just say "Update downloaded, please restart!". I have tried to find out how this was done, so i have been looking in the source code and found some things.
Here is some code that i found:
private void CheckUpdateThread()
{
Program.AddRTLine(Color.Green, "Verifying existence of essential files...\r\n", false);
if (!File.Exists("ICSharpCode.SharpZipLib.dll"))
Util.DownloadURLToFile("https://internal.mcadmin.eu/ICSharpCode.SharpZipLib.dll", "ICSharpCode.SharpZipLib.dll");
if (!File.Exists("LICENSE.txt"))
Util.DownloadURLToFile("https://internal.mcadmin.eu/LICENSE.txt", "LICENSE.txt");
Program.AddRTLine(Color.Green, "Essential file validation completed!\r\n", false);
if (Program.dontUpdate)
{
Program.AddRTLine(Color.Green, "Update checking disabled!!!\r\n", false);
return;
}
UpdateRunning = true;
Program.AddRTLine(Color.Green, "Checking for updates...\r\n", false);
bool isUpdate;
if (Program.dontUpdateMCAdmin || 1 == 1)
{
Program.AddRTLine(Color.Green, "MCAdmin update checking disabled.\r\n", false);
}
else
{
isUpdate = Util.DownloadURLToAndDiff("https://internal.mcadmin.eu/MCAdmin.exe", "MCAdmin.exe.new", "MCAdmin.exe");
if (!isUpdate)
{
if (OutOfDateMCA)
{
Program.AddRTLine(Color.Orange, "MCAdmin update downloaded! Restart MCAdmin to apply update!\r\n", false);
SendAdminMessage("MCAdmin update downloaded, consider restarting.", 4);
}
else
{
Program.AddRTLine(Color.Green, "MCAdmin already up to date!\r\n", false);
}
}
else
{
try
{
if (File.Exists("MCAdmin.exe.old"))
File.Delete("MCAdmin.exe.old");
}
catch { }
try
{
if (File.Exists("MCAdmin.exe"))
File.Delete("MCAdmin.exe");
}
catch { }
if (File.Exists("MCAdmin.exe"))
File.Move("MCAdmin.exe", "MCAdmin.exe.old");
File.Move("MCAdmin.exe.new", "MCAdmin.exe");
OutOfDateMCA = true;
Program.AddRTLine(Color.Orange, "MCAdmin update downloaded! Restart MCAdmin to apply update!\r\n", false);
SendAdminMessage("MCAdmin update downloaded, consider restarting.", 4);
}
}
This code is from a single void in a class called "UpdateManager".
See how it does the whole "MCadmin.exe.old" and "MCadmin.exe.new" files, a bit like shadow copying.
There is more to the updater code, but i don't quite understand.
Here is the SVN:
https://code.google.com/p/mcadminfork/source/browse/
Could anybody help me find out how this updater was acheived?
Thanks.
Util.DownloadURLToAndDiff() does the actual downloading and file comparison. So you probably want to look at that.
Otherwise, it's pretty simple:
Download MCAdmin.exe.new
Delete MCAdmin.exe.old (leftover from previous update)
Try to delete current MCAdmin.exe
If delete fails (file in use probably), rename MCAdmin.exe MCAdmin.exe.old
Rename MCAdmin.exe.new MCAdmin.exe

Categories

Resources