MethodInvoker is repeating once, and displaying output Twice - c#

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

Related

How to save to a file the selected path when using dialog?

What I tried but not working :
At the bottom of windowMain.xaml.cs I added two new methods for saving and loading :
private void SaveFile(string contentToSave, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName);
File.WriteAllText(saveFilePath, contentToSave);
}
private void LoadFile(string loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo = File.ReadAllText(saveFilePath);
}
}
Then for saving in two places :
private void btnRadarFolder_Click(object sender, RoutedEventArgs e)
{
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.ShowNewFolderButton = true;
if (dlg.ShowDialog() == true)
{
SaveFile(textBoxRadarFolder.Text, "radarpath");
textBoxRadarFolder.Text = dlg.SelectedPath;
}
}
private void btnSatelliteFolder_Click(object sender, RoutedEventArgs e)
{
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.ShowNewFolderButton = true;
if (dlg.ShowDialog() == true)
{
SaveFile(textBoxSatelliteFolder.Text, "satellitepath");
textBoxSatelliteFolder.Text = dlg.SelectedPath;
}
}
And for loading at the top :
public MainWindow()
{
InitializeComponent();
LoadFile(textBoxRadarFolder.Text, "radarpath");
LoadFile(textBoxSatelliteFolder.Text, "satellitepath");
But it does nothing no errors no exceptions it's just not loading anything back to the textboxes when running the application and I selected folders first but nothing.
Update :
Saving is working fine.
The problem is with the loading :
At the top I'm doing when running the application :
public MainWindow()
{
InitializeComponent();
LoadFile(textBoxRadarFolder.Text, "radarpath.txt");
LoadFile(textBoxSatelliteFolder.Text, "satellitepath.txt");
But then at the bottom in the LoadFile method I see that the control text to load the content to is empty for some reason even if I entered both textboxes.text to read back it's empty :
The variable loadTo is empty and it should be the textBoxes of the radar and satellite. Why loadTo is empty ?
private void LoadFile(string loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo = File.ReadAllText(saveFilePath);
}
}
This is working I just wonder in case the control in the LoadFile is not TextBox but let's say for example RichTextBox ?
It's working now for my needs but what if I wanted to make the LoadFile method something more generic for any control that have text property content like RichTextBox or Label ? Now I'm using TextBox.
LoadFile(textBoxRadarFolder, "radarpath.txt");
LoadFile(textBoxSatelliteFolder, "satellitepath.txt");
And
private void LoadFile(TextBox loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo.Text = File.ReadAllText(saveFilePath);
}
}

Listbox Item holds data

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

How to get file path from OpenFileDialog and FolderBrowserDialog?

Hey there i started learning C# a few days ago and I'm trying to make a program that copies and pastes files (and replaces if needed) to a selected directory but I don't know how to get the directory and file paths from the openfiledialog and folderbrowserdialog
what am I doing wrong?
Here's the code:
namespace filereplacer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
if (directchoosedlg.ShowDialog() == DialogResult.OK)
{
folderPath = directchoosedlg.SelectedPath;
}
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
choofdlog.ShowDialog();
}
private void replacebtn_Click(object sender, EventArgs e)
{
// This is where i'm having trouble
}
public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
{
File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);
}
}
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder and selected file name you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).
In that case you could get all selected files in string[]:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);
you can store the Path into string variable like
string s = choofdlog.FileName;
To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.
var file = choofdlog.FileName; // for one file
or for multiple files
var files = choofdlog.FileNames; // for multiple files.
To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path
Create this class as Extension:
public static class Extensiones
{
public static string FolderName(this OpenFileDialog ofd)
{
string resp = "";
resp = ofd.FileName.Substring(0, 3);
var final = ofd.FileName.Substring(3);
var info = final.Split('\\');
for (int i = 0; i < info.Length - 1; i++)
{
resp += info[i] + "\\";
}
return resp;
}
}
Then, you could use in this way:
//ofdSource is an OpenFileDialog
if (ofdSource.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(ofdSource.FolderName());
}
Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.
A primitive quick fix that works.
If you only use OpenFileDialog, you can capture the FileName, SafeFileName, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the OpenDialog.
OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path
I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.
String fn = openFileDialog1.SafeFileName;
String path = openFileDialog1.FileName.ToString().Replace(fn, "");

Can I Use Variables from One Method to another?

Can I use a declared variable or a instance of an object from one method to another?
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
string path = null;
path = OpenFile();
}
private string OpenFile()
{
string path = null;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Open source file";
fileDialog.InitialDirectory = "c:\\";
fileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fileDialog.FilterIndex = 2;
fileDialog.RestoreDirectory = true;
Nullable<bool> result = fileDialog.ShowDialog();
if (result == true)
{
path = fileDialog.FileName;
}
textBox1.Text = path;
return path;
}
Now, I want to get that path and write it on excel. how will I do this, please help, I am week old in using C#.
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "sample.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
string path = null;
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
reportGeneratorVM.ReportGenerator(filename, functionName, path);
}
Thanks
Use an instance field to store the value of your variable.
Like so:
public class MyClass
{
// New instance field
private string _path = null;
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
// Notice the use of the instance field
_path = OpenFile();
}
// OpenFile implementation here...
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "st_NodataSet.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
// Reuse the instance field here
reportGeneratorVM.ReportGenerator(filename, functionName, _path);
}
}
Here is a link which describes fields in much more detail than what I could.
Move the string path as a member inside your class, and remove the declaration inside the methods. that should do it
Use string path as a class level variable.
Use static private string path if you want to use it between pages.
Use private string path if you only need to use it on the current page.
you must define the variable as field in your class:
Private string path = null;
use static private string path;

Trouble getting my button to call my class

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?

Categories