Saving files to a folder with a numeric system C# - c#

I am having some trouble with my program. Is there anyway to store an array to a file but every file have a different name. For Example:
1.txt
2.txt
3.txt
4.txt
I am using Visual Studio 2019 and Coding in C#. This is some of the code im using:
string selectedsite = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
string selectedsize = this.comboBox1.GetItemText(this.comboBox2.SelectedItem);
string selectedproduct = this.comboBox1.GetItemText(this.comboBox3.SelectedItem);
string selectedproxies = this.comboBox1.GetItemText(this.comboBox4.SelectedItem);
string selectedprofiles = this.comboBox1.GetItemText(this.comboBox5.SelectedItem);
string path = "d:\\bot\\bot\\Task.txt";
string[] FileInfo = { selectedsite," ", selectedsize, " ", selectedproduct, " ", selectedproxies, " ", selectedprofiles };

You can use File.WriteAllLines method to store an array to a file and every file have a different name.
Here is a code example you can refer to.
int count = 1;
string path =#"C:\Users\Desktop\Test\{0}.txt";
private void button2_Click(object sender, EventArgs e)
{
while (System.IO.File.Exists(string.Format(#"C:\Users\Desktop\Test\{0}.txt", count)))
{
count++;
}
string selectedsite = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
string selectedsize = this.comboBox1.GetItemText(this.comboBox2.SelectedItem);
string selectedproduct = this.comboBox1.GetItemText(this.comboBox3.SelectedItem);
string selectedproxies = this.comboBox1.GetItemText(this.comboBox4.SelectedItem);
string selectedprofiles = this.comboBox1.GetItemText(this.comboBox5.SelectedItem);
string[] FileInfo = { selectedsite, " ", selectedsize, " ", selectedproduct, " ", selectedproxies, " ", selectedprofiles };
var newFileName = string.Format(#"C:\Users\Desktop\Test\{0}.txt", count);
count++;
System.IO.File.WriteAllLines(newFileName, FileInfo);
}

Related

Details entered in windows form will not save to CSV file

the information I enter in my form is not being stored in my CSV file. Just a blank file. the file name updates with todays date.
here is my code.
private void btnSave_Click(object sender, EventArgs e)
{
string date = DateTime.Today.ToString("dd-MM-yyyy"); //get today's date
string filePath = "Policy_" + date + ".csv"; //create a name of the new csv file (including the date)
string delimiter = ","; //comma needed to create new csv file
StringBuilder sb = new StringBuilder();
foreach (DriverDetails driverDetails in driverDet) //go through the List called DriverDetails and examine each object in turn
{
sb.AppendLine(driverDetails.Title + delimiter + driverDetails.FName + delimiter + driverDetails.SName + delimiter + driverDetails.Dob + delimiter + driverDetails.Phone + delimiter + driverDetails.Email + delimiter + driverDetails.Employment + delimiter + driverDetails.Marital + delimiter + driverDetails.HouseNo + delimiter + driverDetails.Street + delimiter + driverDetails.Postcode + delimiter);//uild up a String containing all the data in the List
}
File.WriteAllText(filePath, sb.ToString());
//File.AppendAllText(filePath, sb.ToString()); //add the new string (made up of SEVERAL lines, each representing data from ONE order) to the end of the csv file
MessageBox.Show("Driver details saved to file");
}
I use the following code to fill the driverDet, and then can write the data to the csv file.
class DriverDetails
{
public string Title { get; set; }
public string FName { get; set; }
public string SName { get; set; }
}
List<DriverDetails> driverDet = new List<DriverDetails> {
new DriverDetails { Title = "T1", FName = "F1", SName = "S1"},
new DriverDetails { Title = "T2", FName = "F2", SName = "S2"},
new DriverDetails { Title = "T3", FName = "F3", SName = "S3"}};
You can replace
File.WriteAllText(filePath, csv.ToString());
with
File.AppendAllText(filePath, csv.ToString());

C# How to copy files from one directory to another without overwriting the files in the destinaton directory? [duplicate]

My C# code is generating several text files based on input and saving those in a folder. Also, I am assuming that the name of the text file will be same as input.(The input contains only letters)
If two files has same name then it is simply overwriting the previous file.
But I want to keep both files.
I don't want to append current date time or a random number to the 2nd file name. Instead I want to do it the same way Windows does. If the fisrt file name is AAA.txt , then second file name is AAA(2).txt, third file name will be AAA(3).txt.....N th file name will be AAA(N).txt.
string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray();
foreach (var item in allFiles)
{
//newFileName is the txt file which is going to be saved in the provided folder
if (newFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
{
// What to do here ?
}
}
This will check for the existence of files with tempFileName and increment the number by one until it finds a name that does not exist in the directory.
int count = 1;
string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
string extension = Path.GetExtension(fullPath);
string path = Path.GetDirectoryName(fullPath);
string newFullPath = fullPath;
while(File.Exists(newFullPath))
{
string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
newFullPath = Path.Combine(path, tempFileName + extension);
}
With this code if file name is "Test (3).txt" then it will become "Test (4).txt".
public static string GetUniqueFilePath(string filePath)
{
if (File.Exists(filePath))
{
string folderPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileNameWithoutExtension(filePath);
string fileExtension = Path.GetExtension(filePath);
int number = 1;
Match regex = Regex.Match(fileName, #"^(.+) \((\d+)\)$");
if (regex.Success)
{
fileName = regex.Groups[1].Value;
number = int.Parse(regex.Groups[2].Value);
}
do
{
number++;
string newFileName = $"{fileName} ({number}){fileExtension}";
filePath = Path.Combine(folderPath, newFileName);
}
while (File.Exists(filePath));
}
return filePath;
}
The other examples don't take into account the filename / extension.
Here you go:
public static string GetUniqueFilename(string fullPath)
{
if (!Path.IsPathRooted(fullPath))
fullPath = Path.GetFullPath(fullPath);
if (File.Exists(fullPath))
{
String filename = Path.GetFileName(fullPath);
String path = fullPath.Substring(0, fullPath.Length - filename.Length);
String filenameWOExt = Path.GetFileNameWithoutExtension(fullPath);
String ext = Path.GetExtension(fullPath);
int n = 1;
do
{
fullPath = Path.Combine(path, String.Format("{0} ({1}){2}", filenameWOExt, (n++), ext));
}
while (File.Exists(fullPath));
}
return fullPath;
}
How about just:
int count = 1;
String tempFileName = newFileName;
foreach (var item in allFiles)
{
if (tempFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
{
tempFileName = String.Format("{0}({1})", newFileName, count++);
}
}
This will use the original file name if it's not there, if not it'll take a new file name with the index in brackets (although this code isn't taking the extension into account). If the newly generated name "text(001)" is used then it'll increment until it finds a valid unused file name.
public static string AutoRenameFilename(FileInfo file)
{
var filename = file.Name.Replace(file.Extension, string.Empty);
var dir = file.Directory.FullName;
var ext = file.Extension;
if (file.Exists)
{
int count = 0;
string added;
do
{
count++;
added = "(" + count + ")";
} while (File.Exists(dir + "\\" + filename + " " + added + ext));
filename += " " + added;
}
return (dir + filename + ext);
}
int count= 0;
file is the name of file
while (File.Exists(fullpathwithfilename)) //this will check for existence of file
{
// below line names new file from file.xls to file1.xls
fullpathwithfilename= fullpathwithfilename.Replace("file.xls", "file"+count+".xls");
count++;
}
I was looking for a solution that would move a file, and make sure that if the destination file name is not already taken. It would follow the same logic as Windows and append a number, with brackets after the duplicate file.
The top answer, thanks to #cadrell0, helped me arrive to the following solution:
/// <summary>
/// Generates full file path for a file that is to be moved to a destinationFolderDir.
///
/// This method takes into account the possiblity of the file already existing,
/// and will append number surrounded with brackets to the file name.
///
/// E.g. if D:\DestinationDir contains file name file.txt,
/// and your fileToMoveFullPath is D:\Source\file.txt, the generated path will be D:\DestinationDir\file(1).txt
///
/// </summary>
/// <param name="destinationFolderDir">E.g. D:\DestinationDir </param>
/// <param name="fileToMoveFullPath">D:\Source\file.txt</param>
/// <returns></returns>
public string GetFullFilePathWithDuplicatesTakenInMind(string destinationFolderDir, string fileToMoveFullPath)
{
string destinationPathWithDuplicatesTakenInMind;
string fileNameWithExtension = Path.GetFileName(fileToMoveFullPath);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileToMoveFullPath);
string fileNameExtension = Path.GetExtension(fileToMoveFullPath);
destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, fileNameWithExtension);
int count = 0;
while (File.Exists(destinationPathWithDuplicatesTakenInMind))
{
destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, $"{fileNameWithoutExtension}({count}){fileNameExtension}");
count = count + 1; // sorry, not a fan of the ++ operator.
}
return destinationPathWithDuplicatesTakenInMind;
}
With regard to Giuseppe's comment on the way windows renames files I worked on a version that finds any existing index i.e. (2) in the file name and renames the file as per windows accordingly. The sourceFileName is assumed to be valid and the user is assumed to have write permission on the destination folder by this point:
using System.IO;
using System.Text.RegularExpressions;
private void RenameDiskFileToMSUnique(string sourceFileName)
{
string destFileName = "";
long n = 1;
// ensure the full path is qualified
if (!Path.IsPathRooted(sourceFileName)) { sourceFileName = Path.GetFullPath(sourceFileName); }
string filepath = Path.GetDirectoryName(sourceFileName);
string fileNameWOExt = Path.GetFileNameWithoutExtension(sourceFileName);
string fileNameSuffix = "";
string fileNameExt = Path.GetExtension(sourceFileName);
// if the name includes the text "(0-9)" then we have a filename, instance number and suffix
Regex r = new Regex(#"\(\d+\)");
Match match = r.Match(fileNameWOExt);
if (match.Success) // the pattern (0-9) was found
{
// text after the match
if (fileNameWOExt.Length > match.Index + match.Length) // remove the format and create the suffix
{
fileNameSuffix = fileNameWOExt.Substring(match.Index + match.Length, fileNameWOExt.Length - (match.Index + match.Length));
fileNameWOExt = fileNameWOExt.Substring(0, match.Index);
}
else // remove the format at the end
{
fileNameWOExt = fileNameWOExt.Substring(0, fileNameWOExt.Length - match.Length);
}
// increment the numeric in the name
n = Convert.ToInt64(match.Value.Substring(1, match.Length - 2)) + 1;
}
// format variation: indexed text retains the original layout, new suffixed text inserts a space!
do
{
if (match.Success) // the text was already indexed
{
if (fileNameSuffix.Length > 0)
{
destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}{3}", fileNameWOExt, (n++), fileNameSuffix, fileNameExt));
}
else
{
destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}", fileNameWOExt, (n++), fileNameExt));
}
}
else // we are adding a new index
{
destFileName = Path.Combine(filepath, String.Format("{0} ({1}){2}", fileNameWOExt, (n++), fileNameExt));
}
}
while (File.Exists(destFileName));
File.Copy(sourceFileName, destFileName);
}
You can declare a Dictionary<string,int> to keep the number of times each root file name was saved. After that, on your Save method, just increase the counter and append it to the base file name:
var key = fileName.ToLower();
string newFileName;
if(!_dictionary.ContainsKey(key))
{
newFileName = fileName;
_dictionary.Add(key,0);
}
else
{
_dictionary[key]++;
newFileName = String.Format("{0}({1})", fileName, _dictionary[key])
}
This way, you'll have a counter for each distinct file name: AAA(1), AAA(2); BBB(1)...
It's working fine now. thanks guys for the answers..
string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray();
string tempFileName = fileName;
int count = 1;
while (allFiles.Contains(tempFileName ))
{
tempFileName = String.Format("{0} ({1})", fileName, count++);
}
output = Path.Combine(folderPath, tempFileName );
string fullPath=output + ".xml";

How to store all values in the key named folder using c#

I wrote a text file. The first item of each line from this text file supposed to be key and rest of the items are values. My text file looks like this-
Flensburg;Nordertor;Naval Academy Mürwik;Flensburg Firth
Kiel;Laboe Naval Memorial;Zoological Museum of Kiel University;Kieler Förde
Lübeck;Holstentor;St. Mary's Church, Lübeck;Passat (ship);Burgtor;Lübeck Museum of Theatre Puppets;Trave
For my project purpose, I need to create .json data for each values and store those vales into the key name folder.As I am very new handling this situation I am not getting the correct logic to do this. However I tried in the follwing way by which I can create the key name folder and and only one subfolder into it. But I need to create all values folder inside the key folder. How can I do it.
My POI class from which I read the text file as key value is-
public class POI
{
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public bool ContainsKey(string key) { return this.poi.ContainsKey(key); }
public List<string> GetValue(string key) { return this.poi[key]; }
public void POIList()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
poi.Add(parts[0], new List<string>());
poi[parts[0]] = new List<string>(parts.Skip(1));
}
}
}
in the form1.cs
private void button1_Click(object sender, EventArgs e)
{
JSON_Output Json = new JSON_Output();
Json.ToJsonForLocation(comboBox1.Text);
}
also I set selectedindexchange from combobox2
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
POI poi1 = new POI();
poi1.POIList();
string txt = comboBox1.SelectedItem.ToString();
if (poi1.ContainsKey(txt))
{
List<string> points = poi1.GetValue(txt);
comboBox2.Items.Clear();
comboBox2.Items.AddRange(points.ToArray());
}
}
}
now where the json file generated to sore the value is-
public void ToJsonForLocation(string name)
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "Text_ImageWithHash");
string SubfolderName = Path.Combine(folderName, name);
//string folderName = Path.Combine(startPath, "Text_ImageWithHash");
System.IO.Directory.CreateDirectory(SubfolderName);
string fileName = name + ".json";
var path = Path.Combine(SubfolderName, fileName);
var Jpeg_File = new DirectoryInfo(startPath + #"\Image\" + name).GetFiles("*.jpg");
POIData Poi=new POIData();
Poi.Shorttext = File.ReadAllText(startPath + #"\Short Text\" + name + ".txt");
Poi.GeoCoordinates=GeosFromString(startPath + #"\Latitude Longitude\" + name + ".txt");
Poi.Images=new List<string> { Jpeg_File[0].Name};
string json = JsonConvert.SerializeObject(Poi,Formatting.Indented);
File.WriteAllText(path , json);
}
This is my code output while running the program.
after clicking button 1 Text_image_withHash folder is generated in the configuration directory.
Now if I open the folder I can see fthe following folders which is the key value from text file
After enable button 2 for combobox two the values folder is generated but not in the key folder.but as usual way in the Text_Image_withHash.
But What I want to do is-
To create that kind of folder-structure, simply use a foreach-loop. And String.Split.
Required usings:
using System;
using System.IO;
using System.Text;
using System.Linq;
Example:
// basePath can be anything
var basePath = "C:\Something";
// assume "info" is your CSV.
var infoParts = info.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (infoParts.Length == 0)
{
return;
}
var rootPath = infoParts[0];
Directory.CreateDirectory(Path.Combine(basePath, rootPath));
foreach (var subPath in infoParts.Skip(1))
{
Directory.CreateDirectory(Path.Combine(basePath, rootPath, subPath));
}
Saving JSON-files into these directories could then simply be made by combining the paths in a similar fashion.
I would also suggest some sanitizing of your paths (such as replacing '/' and '\\' with '_' or '-'.
Example implementation:
public void POIList()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new[] { ';' },
StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
{
// Empty line or similar.
continue;
}
string cityName = parts[0];
poi.Add(cityName, new List<string>());
// Add the points of interest to local.
var points = new List<string>(parts.Skip(1));
poi[cityName] = points;
// basePath will have to be retrieved somehow. It's up to you.
string cityDirectoryPath = Path.Combine(basePath, cityName));
// Create a directory for the city.
Directory.CreateDirectory(cityDirectoryPath);
// Create sub-directories for points.
foreach (string point in points)
{
Directory.CreateDirectory(Path.Combine(
cityDirectoryPath, point));
}
}
}
I have just got my answer. This is the solution of the above question.
For POI Class :
public class POI
{
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public bool ContainsKey(string key) { return this.poi.ContainsKey(key); }
public List<string> GetValue(string key) { return this.poi[key]; }
public void POIList()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
{
// Empty line or similar.
continue;
}
string cityName = parts[0];
poi.Add(cityName, new List<string>());
// Add the points of interest to local.
var points = new List<string>(parts.Skip(1));
poi[cityName] = points;
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "FinalJson");
string cityDirectoryPath = Path.Combine(folderName, cityName);
Directory.CreateDirectory(cityDirectoryPath);
}
}
}
the the json output class
public void ToJsonForLocation(string CityName,string PoiName)
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "FinalJson");
string SubfolderName = Path.Combine(folderName, CityName);
System.IO.Directory.CreateDirectory(SubfolderName);
string fileName = PoiName + ".json";
var path = Path.Combine(SubfolderName, fileName);
var Jpeg_File = new DirectoryInfo(startPath + #"\Image\" + PoiName).GetFiles("*.jpg");
POIData Poi=new POIData();
Poi.Shorttext = File.ReadAllText(startPath + #"\Short Text\" + PoiName + ".txt");
Poi.GeoCoordinates = GeosFromString(startPath + #"\Latitude Longitude\" + PoiName + ".txt");
Poi.Images=new List<string> { Jpeg_File[0].Name};
string json = JsonConvert.SerializeObject(Poi,Formatting.Indented);
File.WriteAllText(path,json);
}
this is generated folder and file in this way-
The Final json file for all values

Replacing hundreds of files with one simple check box check

Is there a simple or a more compact way to do this with a large number of files with one check-box (checked/unchecked), i have i think few thousand lines to put inside the code and i can sort them by year, or by type:
private void CheckBox()
{
try
{
switch (checkBox.IsChecked)
{
case true:
{
const string disable_picture100 = "images/disabled/picture100.png";
const string picture100 = "images\\disabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, disable_picture100, content.FileRoot);
const string disable_picture101 = "images/disabled/picture101.png";
const string picture101 = "images\\disabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, disable_picture101, content.FileRoot);
const string disable_picture102 = "images/disabled/picture102.png";
const string picture102 = "images\\disabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, disable_picture102, content.FileRoot);
UpdateImage();
}
break;
case false:
{
const string enable_picture100 = "images/enabled/picture100.png";
const string picture100 = "images\\enabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, enable_picture100, content.FileRoot);
const string enable_picture101 = "images/enabled/picture101.png";
const string picture101 = "images\\enabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, enable_picture101, content.FileRoot);
const string enable_picture102 = "images/enabled/picture102.png";
const string picture102 = "images\\enabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, enable_picture102, content.FileRoot);
UpdateImage();
}
break;
}
}
catch (Exception ex)
{
//ignored
}
}
Thank you!
List<string> fileNames = new List<string>(); //suppose you have names of files in a list
foreach(var name in fileNames)
{
if(checkBox.IsChecked)
{
Records[name].ReplaceContents
("images/disabled/" + name, "images\\disabled\\" + name, content.FileRoot);
}
else
{
Records[name].ReplaceContents
("images/enabled/" + name, "images\\enabled\\" + name, content.FileRoot);
}
}
Using the code below you can specify a directory (where the string says "FilePath". It gets all files with the extension .png
Then it checks once if the checkbox is checked or not.
And then loops over all the files in the enumerator
var allPngFilesInGivenDirectory = Directory.EnumerateFiles("FilePath").Where(x => x.ToLower().EndsWith(".png"));
var fileEnumerable = allPngFilesInGivenDirectory.GetEnumerator();
string partialPath = checkBox.IsChecked ? "enabled" : "disabled";
while (fileEnumerable.MoveNext())
{
string file = Path.GetFileName(fileEnumerable.Current);
string disable_picture = "images/" + partialPath + "/" + file;
string picture = "images\\" + partialPath + "\\" + file;
Records[picture].ReplaceContents(imagesPath, disable_picture, content.FileRoot);
UpdateImage();
}
Is this roughly what you are looking for?
string pictureName;
string newPictureName;
List<string> fileNames = new List<string>();
foreach(var name in fileNames)
{
if (checkBox.IsChecked)
{
pictureName = "images\\disabled\\" + name + ".png";
newPictureName = "images/disabled/" + name + ".png";
}
else
{
pictureName = "images\\enabled\\" + name + ".png";
newPictureName = "images/enabled/" + name + ".png";
}
}
Records[pictureName].ReplaceContents(imagesPath, newPictureName, content.FileRoot);
Let me know if not.

C# checkBox_CheckedChanged Referencing in different files

Requirement: I have a windows application written in C# and I'm trying to add a checkbox to it where if it is checked, than the files from the search will be copied into subdirectories based on zip code.
Problem: When I reference addzipdir_checkBox.Equals(true) from MainForm.cs on a different page SearchProcess.cs I get the error: "addzipdir_checkBox does not exist in the current context". What is the proper way to reference the checkBox_CheckedChanged occurence?
Here's the code on MainForm.cs:
private void addzipdir_checkBox_CheckedChanged(object sender, EventArgs e)
{
if (addzipdir_checkBox.Equals(true))
{
Log("Organize files by zip code.");
}
if (addzipdir_checkBox.Equals(false))
{
Log("Don't Organize files by zip code.");
}
}
Here's the code on SearchProcess.cs generating an error:
if (addzipdir_checkBox.Equals(true))
{
// adds the given lead's agentid and zip code to the targetpath string
string targetzipdir = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP;
// If the given lead's zip code subdirectory doesn't exist, create it.
if (!Directory.Exists(targetzipdir))
{
Directory.CreateDirectory(targetzipdir);
}
targetFileAndPath = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP + "\\" + fullFileName;
} // end if addzipdir_checkBox.Equals(true)
You need to make sure addzipdir_checkBox is public. For this, you need to use the form editor, select the addzipdir_Checkbox and change the property grid 'Modifiers' item to public or internal.
Then, you need to find a way to reference the instance of this form, something like this:
if (myForm.addzipdir_checkBox.Equals(true))
{
...
...
}
I found that if you right click a variable and click "Go To Definition" it's a lot easier to find where the variable is referenced. I right clicked another variable that was called in through the MainForm and found that they were all called through the SearchCriteria file. I had to bring the addzipdir_checkbox value referenced on the MainForm.cs file through the SearchCriteria.cs file and then call it in the SearchProcess.cs file.
Here's my code on the SearchCriteria.cs file:
public class SearchCriteria
{
private String Corp;
private String OrderNumber;
private String Campaign;
private String City;
private String State;
private String Zip;
private String SourcePath;
private String TargetPath;
private bool SearchOR;
private bool SearchAND;
private bool addzipdirectory_checkBox;
public SearchCriteria()
{
}
public SearchCriteria(String Corp,
String OrderNumber,
String Campaign,
String City,
String State,
String Zip,
String SourcePath,
String TargetPath,
bool SearchOR,
bool SearchAND,
bool addzipdirectory_checkBox)
{
this.Corp = Corp;
this.OrderNumber = OrderNumber;
this.Campaign = Campaign;
this.City = City;
this.State = State;
this.Zip = Zip;
this.SourcePath = SourcePath;
this.TargetPath = TargetPath;
this.SearchOR = SearchOR;
this.SearchAND = SearchAND;
this.addzipdirectory_checkBox = addzipdirectory_checkBox;
}
public bool get_addzipdir_checkBox()
{
return addzipdirectory_checkBox;
}
public void set_addzipdir_checkBox(bool x)
{
addzipdirectory_checkBox = x;
}
}
Here's my code on the Searchprocess.cs file:
// Copy the file if ANY of the search criteria have been met
if (found)
{
m_form.Invoke(m_form.m_DelegateAddString, new Object[] {"FOUND: Order_No: " + Order_No +
" barcode: " + barcode +
" MailerCode: " + MailerCode +
" AgentID: " + AgentID +
" City: " + City +
" State: " + State +
" ZIP: " + ZIP});
//passes values to TransferFile
TransferFile(directory, barcode, AgentID, ZIP);
}
} // end for that finds each matching record
}
// find and copy the file to the target directory string ZIP
private void TransferFile(string sourceDir, string filename, string AgentID, string ZIP)
{
string fullFileName = filename + ".pdf";
string fullFileNameAndPath = sourceDir + "\\" + fullFileName;
string targetFileAndPath;
if (m_sc.get_addzipdir_checkBox()==true)
{
// adds the given lead's agentid and zip code to the targetpath string
string targetzipdir = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP;
// If the given lead's zip code subdirectory doesn't exist, create it.
if (!Directory.Exists(targetzipdir))
{
Directory.CreateDirectory(targetzipdir);
}
targetFileAndPath = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP + "\\" + fullFileName;
} // end if addzipdir_checkBox.Equals(true)

Categories

Resources