Server 1 Server2 Server Config Screen
I am trying to make a video game server manager and I have run into an issue. I want the user to be able to have as many servers as they would like. However I cannot figure out through google searching and just regular messing around how to store the information that the user selects to become associated with the Server they create in the list. Basically when you make Server1 it takes the info you selected from the boxes on the config screen and uses them on the server selection page. But, when you make Server2, the configuration overwrites Server1's configuration. I know my code isn't even setup to be able to do this but I would appreciate a push in the right direction as to which type of code I should use.
Tl:dr I want config options to be associated with ServerX in the server list and each server should have unique settings.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string difSelect;
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if(srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
//Text being displayed to the left of the server listbox
mapLabel1.Text = mapSelect;
difLabel1.Text = difSelect;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string[] lines = { mapSelect, difSelect };
System.IO.File.WriteAllLines(#"C:\Users\mlynch\Desktop\Test\Test.txt", lines);
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
newPanel.Visible = false;
}
}
You mentioned in a recent comment that you had tried saving to a .txt file but it overwrote it anytime you tried to make an additional one. If you wanted to continue with your .txt approach, you could simply set a global integer variable and append it to each file you save.
//Variables
string srvName;
string mapSelect;
string difSelect;
int serverNumber = 0;
...
serverNumber++;
string filepath = Path.Combine(#"C:\Users\mlynch\Desktop\Test\Test", serverNumber.ToString(), ".txt");
System.IO.File.WriteAllLines(filepath, lines);
I think below source code will give you some idea about the direction. Let us start with some initializations:
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
mapBox1.Items.Add("Germany");
mapBox1.Items.Add("Russia");
difBox1.Items.Add("Easy");
difBox1.Items.Add("Difficult");
}
This is the event handler of the "Create Server" button. It takes server parameters from the screen and writes to a file named as the server.
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string path = #"C:\Test\" + srvName + ".txt";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(mapSelect);
sw.WriteLine(difSelect);
sw.Flush();
sw.Close();
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
//newPanel.Visible = false;
}
And finally list box event handler is below. Method reads the server parameters from file and displays on the screen.
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
string path = #"C:\Test\" + srvList.SelectedItem + ".txt";
StreamReader sr = new StreamReader(path);
//Text being displayed to the left of the server listbox
mapLabel1.Text = sr.ReadLine(); // mapSelect;
difLabel1.Text = sr.ReadLine(); // difSelect;
}
Please feel free to ask any questions you have.
I ended up figuring out the issue. Basically I ended up deciding on a write to a txt file and then read from it to display the contents of the file in the server select menu. I also added a delete button so you can delete the servers that you created. it does not have full functionality yet but it is there. So here it what I ended up with and it works perfectly. Thank you all for trying to help.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string mapFile;
string difSelect;
string difFile;
int maxPlayers;
string plrSelect;
string plrFile;
string finalFile;
string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string fileName = "config.txt";
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
//Read Server Selection
string srvSelect = srvList.GetItemText(srvList.SelectedItem);
string srvOut = System.IO.Path.Combine(basepath, srvSelect, fileName);
mapFile = File.ReadLines(srvOut).Skip(1).Take(1).First();
difFile = File.ReadLines(srvOut).Skip(2).Take(1).First();
plrFile = File.ReadLines(srvOut).Skip(3).Take(1).First();
//Display Server Selection
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
mapLabel1.Text = mapFile;
difLabel1.Text = difFile;
plrLabel1.Text = plrFile;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Set Server Name
srvName = namBox1.Text;
string finalpath = System.IO.Path.Combine(basepath, srvName);
//Check if server name is taken
if (System.IO.Directory.Exists(finalpath))
{
MessageBox.Show("A Server by this name already exists");
}
else
{
//Add Server to the Server List
srvList.Items.Add(srvName);
//Server Configuration
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
maxPlayers = maxBar1.Value * 2;
plrSelect = "" + maxPlayers;
//Clear New Server Form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Create the Server File
Directory.CreateDirectory(finalpath);
finalFile = System.IO.Path.Combine(finalpath, fileName);
File.Create(finalFile).Close();
//Write to config file
string[] lines = { srvName, mapSelect, difSelect, plrSelect };
System.IO.File.WriteAllLines(#finalFile, lines);
//Return to srvList
newPanel.Visible = false;
}
}
}
Related
I'm trying to get specific data from an .ini file and display it in GridView. The .ini file is updated with information from the last cut a saw made, and every time the file is updated I want the new information displayed in a new row. The problem I keep running into is that the method I have for populating the grid viewer is repeating once every time the file is changed. Sometimes it displays the correct information twice, and sometimes it displays incorrect information once, and then the second time the correct information is displayed.
I added a check using a bool variable to try to stop this, but that hasn't stopped it from outputting twice.
using System.Text.RegularExpressions;
namespace outputViewer
{
public partial class outputViewer : Form
{
//Declare variables for filepath and create a new dictionary
private string iniFilePath;
private string vjob = "";
private string vpart = "";
private string vname = "";
private string vlength = "";
private string vwidth = "";
private string vheight = "";
private string vgrade = "";
private string vcenterLine = "";
bool populate = false; //If PopulateIniDataGrid has been called turn true
public outputViewer()
{
InitializeComponent();
}
//Watch .ini file for changes
public void Watch()
{
var watcher = new FileSystemWatcher(Path.GetDirectoryName(iniFilePath), Path.GetFileName(iniFilePath))
{
EnableRaisingEvents = true,
NotifyFilter = NotifyFilters.LastWrite
};
watcher.Changed += OnFileChanged;
}
//On file change reset bool variable and call ReadIniFile method
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
populate = false;
ReadIniFile();
}
//Reads .ini file using WriteSafeReadAllLines Method, and extracts data for Output
private void ReadIniFile()
{
var iniFileLines = WriteSafeReadAllLines(iniFilePath);
var currentSection = "";
foreach (var line in iniFileLines)
{
//Code sorting through data for output
}
//Check if PopulateIniDataGridView has been called
if (!populate)
{
PopulateIniDataGridView();
populate = true;
}
}
//Set filepath of .ini file
private void setFilePathToolStripMenuItem_Click(object sender, EventArgs e)
{
//Create new openFileDialog object
var openFileDialog = new OpenFileDialog
{
//File type filters for openFileDialog and set default directory to MyDocuments
Filter = "INI files (*.ini)|*.ini|All files (*.*)|*.*",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
//If Successful
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
iniFilePath = openFileDialog.FileName;
selectedIniFileLabel.Text = iniFilePath;
}
Watch();
}
//Convert method converts mm to feet-inches-sixteenths
private void Convert(ref string imperial)
//Allow reading file when open by another application
public string[] WriteSafeReadAllLines(string path)
private void PopulateIniDataGridView()
{
//Convert metric to imperial
Convert(ref vwidth);
Convert(ref vheight);
Convert(ref vlength);
Convert(ref vcenterLine);
Invoke(new MethodInvoker(delegate
{
scOutputGridView.Rows.Add(vjob, vname, vpart, vlength, vwidth, vheight, vgrade);
}));
}
}
}
I'm creating simple launcher for my other application and I need advise on logical part of the program. Launcher needs to check for connection, then check for file versions (from site), compare it with currently downloaded versions (if any) and if everything is alright, start the program, if not, update (download) files that differs from newest version. The files are:
program.exe, config.cfg and mapFolder. The program.exe and mapFolder must be updated, and config.cfg is only downloaded when there is no such file. Additionaly mapFolder is an folder which contains lots of random files (every new version can have totally different files in mapFolder).
For the file version I thought I would use simple DownloadString from my main site, which may contain something like program:6.0,map:2.3, so newest program ver is 6.0 and mapFolder is 2.3. Then I can use FileVersionInfo.GetVersionInfo to get the version of current program (if any) and include a file "version" into mapFolder to read current version.
The problem is I dont know how to download whole folder using WebClient and what's the best way to do what I want to do. I've tried to download the mapFolder as zip and then automatically unpack it, but the launcher need to be coded in .net 3.0.
Here is my current code, that's just a prototype to get familiar with whole situation, dont base on it.
`
WebClient wc = new WebClient();
string verifySite = "google.com/downloads/version";
string downloadSite = "google.com/downloads/program.exe";
Uri verifyUri, downloadUri = null;
string userVer, currVer = "";
string downloadPath = Directory.GetCurrentDirectory();
string clientName = "program.exe";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(FileDownloaded);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(FileDownloadProgress);
chckAutorun.Checked = Properties.Settings.Default.autorun;
checkConnection();
if(!checkVersion())
downloadClient();
else
{
pbDownload.Value = 100;
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
}
private bool checkConnection()
{
verifyUri = new Uri("http://" + verifySite);
downloadUri = new Uri("http://" + downloadSite);
WebRequest req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
verifyUri = new Uri("https://" + verifySite);
downloadUri = new Uri("https://" + downloadUri);
req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
return false;
}
private void downloadClient()
{
try
{
wc.DownloadFileAsync(downloadUri, Path.Combine(downloadPath, clientName));
}
catch { }
}
private bool checkVersion()
{
lblProgress.Text = "checking for updates";
try
{
currVer = FileVersionInfo.GetVersionInfo(Path.Combine(downloadPath, clientName)).FileVersion;
}
catch {
currVer = "";
}
try
{
userVer = wc.DownloadString(verifyUri);
}
catch {
userVer = "";
}
return currVer == userVer && currVer != "";
}
private void FileDownloaded(object sender, AsyncCompletedEventArgs e)
{
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
private void FileDownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
long received = e.BytesReceived / 1000;
long toReceive = e.TotalBytesToReceive / 1000;
lblProgress.Text = string.Format("{0}KB {1}/ {2}KB", received, Repeat(" ", Math.Abs(-5 + Math.Min(5, received.ToString().Length))*2), toReceive);
pbDownload.Value = e.ProgressPercentage;
}
private void btnPlay_Click(object sender, EventArgs e)
{
btnPlay.Enabled = false;
if(checkVersion())
{
lblProgress.Text = "Starting...";
Process.Start(Path.Combine(downloadPath, clientName));
this.Close();
}
else
{
downloadClient();
}
}
public static string Repeat(string instr, int n)
{
if (string.IsNullOrEmpty(instr))
return instr;
var result = new StringBuilder(instr.Length * n);
return result.Insert(0, instr, n).ToString();
}
private void chckAutorun_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.autorun = chckAutorun.Checked;
Properties.Settings.Default.Save();
}`
I've managed to achieve what I need by enabling autoindex on web server and download string of files in folder ending with .map .
string mapSite = wc.DownloadString(new Uri("http://" + mapsSite));
maps = Regex.Matches(mapSite, "<a href=\"(.*).map\">");
foreach (Match m in maps)
{
string mapName = m.Value.Remove(0, 9).Remove(m.Length - 11);
downloaded = false;
wc.DownloadFileAsync(new Uri("http://" + mapsSite + mapName), Path.Combine(downloadPath, #"mapFolder/" + mapName));
while (!downloaded) { }
}
Here is my AddReservation Form code. Notice that I call the Piper.WritePiper() method and pass in the Name and Seat that the user enters. I'm not sure why this isn't working. I'm not getting any errors or anything. I am simply just wanting a user to be able to enter their name and seat that they would like to take on the plane and then update the file. Please tell me what I am doing wrong... Thank you in advance!!
public partial class frmAddReservation : Form
{
public frmAddReservation()
{
InitializeComponent();
}
List<Seating> piperSeating = new List<Seating>();
List<Seating> cessnaSeating = new List<Seating>();
private void frmAddReservation_Load(object sender, EventArgs e)
{
piperSeating = Piper.GetPiperReservations();
cessnaSeating = Cessna.GetCessnaReservations();
}
private void btnShowPiper_Click(object sender, EventArgs e)
{
listFlight.Items.Add("Piper Seating Chart:");
listFlight.Items.Add("");
//loop through all the seats
foreach (Seating plane in piperSeating)
{
// add the name of plane to the listbox
listFlight.Items.Add(plane.Name + " " + plane.Seat);
}
}
private void btnAddPiper_Click(object sender, EventArgs e)
{
string Name;
int Seat;
if (DataValid())
{
Name = txtName.Text;
Seat = Convert.ToInt16(txtSeat.Text);
Piper.WritePiper(Name, Seat);
}
}
private bool DataValid()
{
bool isOK = false;
if (CheckSeat(txtSeat))
{
isOK = true;
}
return isOK;
}
private bool CheckSeat(TextBox tbox)
{
bool isOK = true;
try
{
Convert.ToDouble(tbox.Text);
}
catch
{
isOK = false;
}
return isOK;
}
}
Here is my Piper.cs class:
public static class Piper
{
private const string dir = #"Z:\Desktop\Windows 7 Files\C#.net\Reservations\Reservations\Reservations\";
private const string path = dir + "PiperDat.txt";
public static List<Seating> GetPiperReservations()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
StreamReader textIn =
new StreamReader(
new FileStream(path, FileMode.Open, FileAccess.Read));
List<Seating> personList = new List<Seating>();
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split(',');
Seating person = new Seating();
person.Name = columns[0];
person.Seat = Convert.ToInt16(columns[1]);
personList.Add(person);
}
textIn.Close();
return personList;
}
public static void WritePiper(string Name, int Seat)
{
List<Seating> piperSeating = new List<Seating>();
piperSeating = Piper.GetPiperReservations();
StreamWriter textOut =
new StreamWriter(
new FileStream(path, FileMode.Open, FileAccess.Write));
foreach (Seating plane in piperSeating)
{
Name = plane.Name;
Seat = plane.Seat;
textOut.Write(Name + ",");
textOut.WriteLine(Seat);
}
}
}
Look at the WritePiper method.
It just reads the file and then writes it back, without any changes. The values in the parameters are ignored, the parameters are just used as temporary storage for the data when it is written to the file.
You need to include the values in the parameters as an item, either by adding it to the list, or by writing it to the file along with the items in the list.
Example:
Seating person = new Seating();
person.Name = Name;
person.Seat = Seat;
piperSeating.Add(person);
I think the cause of your issue might be having forgotten the closure of the file, in alternative you might force the text to flush with textOut.Flush().
Try adding textOut.Close() at the end of the WritePiper(...) method.
I have tried lots of codes posted here. And another places.
It doesn't do what want to do.
First See the code:
Load Button:
private void LoadBtn_Click(object sender, EventArgs e)
{
TextReader testTxt = new StreamReader(ItemBaseInfosPath);
string read;
do
{
read = testTxt.ReadLine();
if (read.Contains(IDTxt.Text))
{
ConquerItemBaseInformation CIBI = new ConquerItemBaseInformation();
CIBI.Parse(read);
NameTxt.Text = CIBI.Name;
LevelTxt.Text = Convert.ToString(CIBI.Level);
MaxAttackTxt.Text = Convert.ToString(CIBI.MaxAttack);
MinAttackTxt.Text = Convert.ToString(CIBI.MinAttack);
PhysicalTxt.Text = Convert.ToString(CIBI.PhysicalDefence);
DodgeTxt.Text = Convert.ToString(CIBI.Dodge);
MagicAttackTxt.Text = Convert.ToString(CIBI.MagicAttack);
MagicDefTxt.Text = Convert.ToString(CIBI.MagicDefence);
AttackRangeTxt.Text = Convert.ToString(CIBI.AttackRange);
PriceTxt.Text = Convert.ToString(CIBI.ConquerPointsWorth);
break;
}
else
{
MessageBox.Show("Item Not Found.");
}
} while (read != null);
Save Button:
private void SaveBtn_Click(object sender, EventArgs e)
{
TextReader testTxt = new StreamReader(ItemBaseInfosPath);
string read, read1, read2, read3, read4, read5, read6,
read7, read8, read9, read10;
do
{
read = testTxt.ReadLine();
if (read.Contains(IDTxt.Text))
{
ConquerItemBaseInformation CIBI = new ConquerItemBaseInformation();
CIBI.Parse(read);
CIBI.Name = NameTxt.Text;
CIBI.Level = Convert.ToByte(LevelTxt.Text);
CIBI.MaxAttack = Convert.ToByte(MaxAttackTxt.Text);
MessageBox.Show(read);
break;
}
} while (read != null);
}
Load Button is working Great! Without problems. The problems in Save Button.
I got now the line, Example:" 111003##IronHelmet##21##0##15##0##0##0##0##0##0##0##150##0##0##0##3##0##0##0##0##3899##3899##0##0##0##0##0##0##0##0##0##1##1000##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##0##Warrior'sHelmet##None##5##0##0##0##2020##500##"
111003 is the ID, IronHelmet is the Name, 15 is the level.
It loaded. I want to save it. (Note for each of these have it's TextBox.
It's ItemEditor program, so I want when I edit anything in TextBox and Press "Save button"
It replace each of the edited things and save the text file again!:)
(Note: String.Replace("", ""); This code if I use it and the textbox that should edit, if it's value (Text) is 0 then it will change All Values of 0 in the Line! = Fail )
I hope you understand me!
I have a Windows Form application. What this application does, is let the user browse to a drive/folder they wish to have files renamed for. This app renames files that have "invalid" characters (that are defined in a RegEx pattern).
What i want to happen here is, after the user decides which drive/folder to use, a datagridview pops up showing the user files in the drive/folder that are going to be renamed. The user then clicks a button to actually rename the files. I'm having trouble though getting the code for my button in DriveRecursion_Results.cs set up. Can anybody help me? Code plz -- i'm extremely new to this and need syntax to look at to understand.
Form1 code:
namespace FileMigration2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.Empty;
//Now, we want to use the path information to population our folder selection initial location
string initialPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion_Results dw = new DriveRecursion_Results();
dw.Show();
dw.DriveRecursion(retPath);
result = retPath;
}
return result;
}
}
}
DriveRecursion_Results.cs code: [the button is in here that i need help with!]
namespace FileMigration2
{
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
//recurse through files. Let user press 'ok' to move onto next step
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
//string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
dataGridView1.Rows.Clear();
try
{
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
string fileNameOnly = Path.GetFileName(fileNames);
string pathOnly = Path.GetDirectoryName(fileNames);
DataGridViewRow dgr = new DataGridViewRow();
filePath.Add(fileNames);
dgr.CreateCells(dataGridView1);
dgr.Cells[0].Value = pathOnly;
dgr.Cells[1].Value = fileNameOnly;
dataGridView1.Rows.Add(dgr);
filePath.Add(fileNames);
}
else
{
DataGridViewRow dgr2 = new DataGridViewRow();
dgr2.Cells[0].Value = "No Files To Clean Up";
dgr2.Cells[1].Value = "";
}
}
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
sw.Write(e);
}
}
private void button1_Click(object sender, EventArgs e)
{
//What do i type in here to call my FileCleanUp method???
}
}
SanitizeFileNames.cs code:
namespace FileMigration2
{
public class SanitizeFileNames
{
public static void FileCleanup(List<string>filePath)
{
string regPattern = "*[\\~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
}
}
}
Any help is appreciated!
Thanks :)
Put
public partial class DriveRecursion_Results : Form {
List<string> filePath;
and in driveRecursion method, just use
filePath = new List<string>();
and in the action button method, why don't you do
if(filePath != null)
SanitizeFileNames.FileCleanup(filePath);
You call filePath.Add twice ?
Your 'else' is in the wrong place too.
What is dgr2?