I am a newbie in C# I just have a doubt.I have two group boxes,each of them has three radio buttons in it,If I want to select each radio button from each groupbox and write a condition for that ,,How can I do that. Below is the code:
public void SaveMyTextBoxContents()
{
string path = usbLetter +"MSREAD.txt";
if (lbItems.SelectedIndex == -1)
{
if (rdBtnMed.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = medium + " " + item;
outputFile.WriteLine(saveText);
}
}
}
}
else if (rdBtnMedium.Checked && rdBtnN.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = mediumNo + " " + item;
outputFile.WriteLine(saveText);
}
}
}
}
}
Please help me I got stuck up with this.
Thanks Krik
Make small panels to the size of radio button pairs and place those radio buttons on them (two each). E.g separate for male, female; separate for young, old etc. The panel won't show on run. This will work Insha'Allah in a group box too.
You're brackets are off, so it only checks rdBtnMedium and rdBtnN if lblItems.SelectedIndex != 1. Here's what I think you need:
if (lbItems.SelectedIndex == -1)
{
if (rdBtnMed.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = medium + " " + item;
outputFile.WriteLine(saveText);
}
}
}
else if (rdBtnMedium.Checked && rdBtnN.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = mediumNo + " " + item;
outputFile.WriteLine(saveText);
}
}
}
}
Related
I have a DataTable which contains approximately 150.000 rows. I try to compare those rows to Files (approximately 200.000 files) in a specific folder. My code looks like:
foreach (DataRow row in KundenundDateinamenohneDoppelte.Rows)
{
OrdnerSchadenanlage = #"" + Settings.Default.PathtoKundenablage + "\\Kundenablage\\";
foreach (string item in listbox2.Items)
{
if (item == "Leerzeile")
{
OrdnerSchadenanlage += " ";
}
else if (item == "-" || item == ",")
{
OrdnerSchadenanlage += item;
}
else
{
OrdnerSchadenanlage += row[item].ToString().Replace("/", " u. ").Replace(#"""", "").Replace("00:00:00", "");
}
}
if (!Directory.Exists(OrdnerSchadenanlage))
{
Directory.CreateDirectory(OrdnerSchadenanlage);
}
DirectoryInfo DIR = new DirectoryInfo(Settings.Default.PathtoGesamtablage);
FileInfo[] FILES = DIR.GetFiles("*.*");
DirectoryInfo[] DIRECTORIES = DIR.GetDirectories();
foreach (FileInfo f in FILES)
{
double _fileSize = new System.IO.FileInfo(f.FullName).Length;
string filenametocheck = string.Empty;
string filenamewithoutklammern = f.Name;
string pattern = #"\s\([0-9]+\)\.";
bool m = Regex.IsMatch(filenamewithoutklammern, pattern);
if (m == true)
{
filenamewithoutklammern = Regex.Replace(filenamewithoutklammern, pattern, ".");
filenametocheck = filenamewithoutklammern;
}
else
{
filenametocheck = f.Name;
}
if (System.IO.Path.GetFileNameWithoutExtension(filenametocheck) == row["Dateiname"].ToString() && Math.Ceiling(_fileSize / 1024) == Convert.ToDouble(row["Größe in kB"].ToString()))
{
string folderfound = "";
if (newtable.Rows.Count > 0)
{
foreach (DataRow dr in newtable.Rows)
{
if (dr["Suchart"].ToString() == "beginnend")
{
if (f.Name.StartsWith(dr["Dateiname"].ToString()))
{
folderfound = dr["Ordnername"].ToString();
break;
}
else
{
folderfound = string.Empty;
}
}
else
{
if (f.Name.Contains(dr["Dateiname"].ToString()))
{
folderfound = dr["Ordnername"].ToString();
break;
}
else
{
folderfound = string.Empty;
}
}
}
if (folderfound != string.Empty)
{
OrdnermitUnterodner = OrdnerSchadenanlage + "\\" + folderfound + "";
if (!Directory.Exists(OrdnermitUnterodner))
{
Directory.CreateDirectory(OrdnermitUnterodner);
}
if (!File.Exists(System.IO.Path.Combine(OrdnerSchadenanlage, f.Name)) && !File.Exists(System.IO.Path.Combine(OrdnermitUnterodner, f.Name)))
{
File.Copy(f.FullName, System.IO.Path.Combine(OrdnermitUnterodner, f.Name));
File.Delete(f.FullName);
//kopiervorgang.Rows.Add(1, "Copied file " + f.FullName + " to " + System.IO.Path.Combine(OrdnermitUnterodner, f.Name) + "\n");
}
}
else
{
if (!File.Exists(System.IO.Path.Combine(OrdnerSchadenanlage, f.Name)) && !File.Exists(System.IO.Path.Combine(OrdnermitUnterodner, f.Name)))
{
File.Copy(f.FullName, System.IO.Path.Combine(OrdnerSchadenanlage, f.Name));
File.Delete(f.FullName);
//kopiervorgang.Rows.Add(1, "Copied file " + f.FullName + " to " + System.IO.Path.Combine(OrdnerSchadenanlage, f.Name) + "\n");
}
}
}
else
{
if (!File.Exists(System.IO.Path.Combine(OrdnerSchadenanlage, f.Name)) && !File.Exists(System.IO.Path.Combine(OrdnermitUnterodner, f.Name)))
{
File.Copy(f.FullName, System.IO.Path.Combine(OrdnerSchadenanlage, f.Name));
File.Delete(f.FullName);
//kopiervorgang.Rows.Add(1, "Copied file " + f.FullName + " to " + System.IO.Path.Combine(OrdnerSchadenanlage, f.Name) + "\n");
}
}
}
else
{
//kopiervorgang.Rows.Add(0, "Copy failed cause there is no match between filenmame and filesize.\n");
}
}
GC.Collect();
progressrow++;
double Percentage = Convert.ToDouble(progressrow) * 100 / KundenundDateinamenohneDoppelte.Rows.Count;
übertragenworker.ReportProgress(0, Percentage);
}
kopiervorgang.Rows.Add(0, "Übertragung abgeschlossen.");
e.Result = kopiervorgang;
}
This works just fine, Files are getting compared and copied to the destined folder. However for processing just 0.2 % of this task my application needs about 1 hour. Calculated to 100% this should be about 17 days.
Is there any way to make this loop more efficient and faster?
This needs what we call "refactoring" to achieve the desired optimization. There are too many nested loops containing code that can be removed from the loops.
One particular kind of refactoring needed is removing everything that is not affected by the loops from inside the loops. Everything that depends on these things that are not related to the loops, can also then be removed (as long as there is no dependency on the loop, e.g. loop variable).
For example, I would start with removing this chunk from the loop because it is non-trivial (expensive, computationally) but it does not depend on the loop at all.
// should remove these lines from the loop!
DirectoryInfo DIR = new DirectoryInfo(Settings.Default.PathtoGesamtablage);
FileInfo[] FILES = DIR.GetFiles("*.*");
DirectoryInfo[] DIRECTORIES = DIR.GetDirectories();
The process of refactoring involve identifying these cases and improving code by putting them in suitable better places. Another thing to do is split the big method into smaller methods.
More things that can be removed from loop:
OrdnerSchadenanlage = #"" + Settings.Default.PathtoKundenablage + "\\Kundenablage\\";
string pattern = #"\s\([0-9]+\)\.";
FILES
Now that FILES is removed from the loop, we can also remove this from the loop: double _fileSize = new System.IO.FileInfo(f.FullName).Length; Since we are looping all the FILES we can get all the sizes ONCE not for each data row, this is because the files are the same for each row in KundenundDateinamenohneDoppelte.Rows (the main foreach).
Note: fileSize should be long not double.
The way to remove this from the loop is to create a dictionary of file sizes. For example:
// outside the loop, just under `FILES`
Dictionary<string, long> fileSizes = FILES.Select(file => new { file.FullName, new System.IO.FileInfo(file.FullName).Length }).ToDictionary(fl => fl.FullName, fl => fl.Length);
You can then use this dictionary like this to get the file size without doing many calls to FileInfo.Length!
// inside the FILES loop, I replace double with long
long _fileSize = fileSizes[f.FullName];
newtable
I don't know what's inside of newtable and how does it change, but I don't see it depending on the outside loops, therefore it should be possible to remove this whole section from the nested loops:
foreach (DataRow dr in newtable.Rows) {
if (dr["Suchart"].ToString() == "beginnend") {
if (f.Name.StartsWith(dr["Dateiname"].ToString())) {
folderfound = dr["Ordnername"].ToString();
break;
} else {
folderfound = string.Empty;
}
} else {
if (f.Name.Contains(dr["Dateiname"].ToString())) {
folderfound = dr["Ordnername"].ToString();
break;
} else {
folderfound = string.Empty;
}
}
}
From the following code I am trying to save listView items in a text file. But it doesn't save the items of listView in text file even not generating any error. My listView has a single column. Please identify What I am missing in this code.
private void saveAttemptsStatus()
{
var sw = new System.IO.StreamWriter("D:\\AlphaNumDataSum_" + txt_LUsername.Text);
foreach (ListViewItem item in list_Count.Items)
{
sw.Write(item + "\r\n");
}
sw.Close();
}
private void CountAttemps()
{
int numberOfItems = list_Count.Items.Count;
if (numberOfItems != 10)
{
if (username == txt_LUsername.Text && password == txt_LPassword.Text)
{
list_Count.Items.Add("correct");
txt_LUsername.Text = string.Empty;
txt_LPassword.Text = string.Empty;
}
else
{
list_Count.Items.Add("inCorrect");
txt_LUsername.Text = string.Empty;
txt_LPassword.Text = string.Empty;
}
}
else
{
saveAttemptsStatus();
MessageBox.Show("Thank You!");
}
}
Try changing your code to the following version and see if this works:
private void saveAttemptsStatus()
{
var filePath = "D:\\AlphaNumDataSum_" + txt_LUsername.Text;
using(sw = new System.IO.StreamWriter(filePath)){
foreach (ListViewItem item in list_Count.Items)
{
sw.WriteLine(item.Text);
}
}
}
I have sorted it out by creating a new file.
private void saveAttemptsStatus()
{
try
{
var sw = new System.IO.StreamWriter("D:\\AlphaNumDataSum_" + txt_LUsername.Text + "_Attempts");
foreach (ListViewItem item in list_Count.Items)
{
sw.Write(item + "\r\n");
}
sw.Close();
}
catch (System.IO.FileNotFoundException ex)
{
System.IO.File.Create("D:\\AlphaNumDataSum_" + txt_LUsername.Text + "_Attempts");
var sw = new System.IO.StreamWriter("D:\\AlphaNumDataSum_" + txt_LUsername.Text + "_Attempts");
foreach (ListViewItem item in list_Count.Items)
{
sw.Write(item + "\r\n");
}
sw.Close();
}
}
I have a whole bunch of document which have a plain text place marker like ~{fieldToBeReplaced} and I want it to be replaced with a Merge field.
I have the following code which kind of inserts the merge field and then inserts the text << MERGEFIELD_NAME >>.
What I want is it to be the mergefield with the name displayed just like it would be if i were to Insert->Merge Field in word.
//linqPad Script
void Main()
{
Console.WriteLine("::::: Replacing BookMarks ::::: ");
//Search And Replace bookmarks
try
{
var replaceDir = new DirectoryInfo(saveFileLocation);
var bookmarkFiles = replaceDir.GetFiles().ToList();
foreach (var bkmFile in bookmarkFiles)
{
if (SearchReplaceBookmarks(bkmFile.FullName))
{
Console.WriteLine("Bookmarks Replace:" + bkmFile.Name + " ::: ");
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR: ::: " + ex.Message);
}
}
static string startDir = Path.GetDirectoryName(Util.CurrentQueryPath);
string saveFileLocation = startDir + #"\Converted\";
private List<fieldReplace> fieldList = new List<fieldReplace>() {
//new fieldReplace("",""),
new fieldReplace("~{U-nm}","_Doctor"),
new fieldReplace("~{P-nl}","_Patient_Surname","Patient_Firstname"),
new fieldReplace("~{DOBN}","_Patient_DOB"),
new fieldReplace("~{U-ph","_Doctor_PhoneWork"),//Surgeon Business
new fieldReplace("~{U-pm}","_Doctor_PhoneMobile")//Surgeon After Hours
}
// Define other methods and classes here
private bool SearchReplaceBookmarks(string filename)
{
try
{
WordDocument wordDocument = new WordDocument(filename);
//Adds one section and one paragraph to the document
foreach (var fld in fieldList)
{
var replaceBookmark = wordDocument.Find(fld.TextToReplace, false, true);
//if the bookmark is in the list then
while (replaceBookmark != null)
{
//Find and replace text with merge field.
var paragraph = new WParagraph(wordDocument);
for (int i =0 ; i<= fld.FieldNames.Length-1;i++){
var field = paragraph.AppendField(fld.FieldNames[i], FieldType.FieldMergeField);
field.FieldType = FieldType.FieldMergeField;
if (i < fld.FieldNames.Length - 1) { paragraph.AppendText(", ");}
}
var selection = new TextSelection(paragraph, 0, paragraph.Text.Length);
wordDocument.Replace(fld.TextToReplace, selection, true, true); //This is where the Merge Field is meant to be inserted
replaceBookmark = wordDocument.FindNext(paragraph, fld.TextToReplace, false, true);
}
}
//Debug.Write( wordDocument.MailMerge.MappedFields);
wordDocument.Save(filename, FormatType.Docx);
wordDocument.Close();
return true;
}
catch (Exception ex)
{
Console.WriteLine("ERROR:" + filename + " ::: " + ex.Message);
return false;
}
}
private class fieldReplace
{
public fieldReplace(string oldText, params string[] newNewFieldName)
{
this.TextToReplace = oldText;
this.FieldNames = newNewFieldName;
}
public string TextToReplace { get; set; }
public string[] FieldNames { get; set; }
}
On analyzing on your mentioned scenario,
1) Finding the place holder text from the Word document.
2) Replacing the place holder text with the merge fields and the fields to be replaced as such in MS Word document.
Yes, using DocIO the place holder text can be replaced with merge fields as equivalent to MS Word. We have modified your code to achieve your requirement. We have used TextBodyPart overload of the Replace() method. Please find the below code snippet.
Modified Code Snippet
TextBodyPart bodyPart = new TextBodyPart(wordDocument);
bodyPart.BodyItems.Add(paragraph); wordDocument.Replace(fld.TextToReplace, bodyPart, true, true);
For further questions please contact our support team at support#syncfusion.com to get a prompt assistance on this.
Maybe I'm overthinking this. I've got a working method for writing to a text file, and reading from it.
Writing:
public void SaveNotes()
{
using (StreamWriter save= new StreamWriter("notes.txt", true))
{
foreach (var element in collection)
{
spara.Write(element.Prio+ " " + element.Note+ "\n");
}
}
}
Now I'm trying to design a method that looks for any '0' in my list, and overwrite the entire line.
Is there any easier way to tell the program that all lines containing a '0' should be overwritten with blankspaces? Any input much appreciated.
public static void Delete(Note note)
{
using (StreamWriter remove = new StreamWriter("notes.txt"))
{
Regex rgx = new Regex("");
foreach (var element in collection)
{
while (element.Notering.Contains("0"))
{
rgx.Replace(element.Note, "");
rgx.Replace(element.Prio, "");
}
}
}
}
Why don't you combine two of them?
public void SaveNotes()
{
using (StreamWriter save= new StreamWriter("notes.txt", true))
{
foreach (var element in collection)
{
if (element.Prio.IndexOf('\0') < 0 && element.Note.IndexOf('\0') < 0)
spara.Write(element.Prio+ " " + element.Note+ "\n");
else spara.Write(" \n");
}
}
}
I have attached my code below. I am trying to get the message box to go away after one pop up until another action within the application triggers it.
using (VIModel vi = new VIModel())
{
var VideoFiles = vi.VI_VIDEO_FILES.Where(a => a.SEGMENT_ID == segmentId);
foreach (var vf in VideoFiles)
{
string location = vf.URL;
location = location.Replace('/', '\\');
string[] smain = location.Split('\\');
string unamemain = smain.Last().ToString();
string fileToCopySource = Path.Combine(inputDirectory, location);
string fileToCopyDestination = Path.Combine(outputDirectory, unamemain);
foreach (char c in fileToCopySource)
{
if (fileToCopySource.Contains(c))
{
// notify user that the inputDirectory isn't valid
MessageBox.Show("FOO");
}
}
if (!File.Exists(fileToCopySource))
{
// notify user that file doesn't exist
MessageBox.Show("FOO");
}
//File.Copy(inputDirectory + location, outputDirectory + unamemain, true);
File.Copy(fileToCopySource, fileToCopyDestination, true);
lbConsole.Items.Add("Moved " + location + " from: " + inputDirectory + " to " + fileToCopyDestination);
}
}
Your code is alerting multiple times -- once for every "alertable" condition it finds, i.e. input directory not valid. What you need to do is record the fact that anything caused the condition that will need to be alerted, and then alert only once, outside of the loop:
bool needAlert = false;
foreach (char c in fileToCopySource)
{
if (fileToCopySource.Contains(c))
{
needAlert = true;
break; // no more looping needed.
}
}
if(needAlert) MessageBox.Show("FOO"); // notify user that the inputDirectory isn't valid