Saving ListView items in a text file in c# - c#

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

Related

How can I search for a specific attachment in outlook

I am trying to retrieve a specific attachment in Outlook to save to my folder.
Everything works great but it seems to save all the attachments in the "Inbox" Folder instead of the specific one I am looking for.
This is what I have at the moment:
static void EnumerateFoldersInDefaultStore()
{
Outlook.Application Application = new Outlook.Application();
Outlook.Folder root = Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
EnumerateFolders(root);
}
static void EnumerateFolders(Outlook.Folder folder)
{
Outlook.Folders childFolders = folder.Folders;
if (childFolders.Count > 0)
{
foreach (Outlook.Folder childFolder in childFolders)
{
if (childFolder.FolderPath.Contains("Inbox"))
{
Console.WriteLine(childFolder.FolderPath);
EnumerateFolders(childFolder);
}
}
}
Console.WriteLine("Checking in " + folder.FolderPath);
IterateMessages(folder);
}
static void IterateMessages(Outlook.Folder folder)
{
string fileName = "Reports.pdf";
var fi = folder.Items;
if (fi != null)
{
try
{
foreach (Object item in fi)
{
Outlook.MailItem mi = (Outlook.MailItem)item;
var attachments = mi.Attachments;
if (attachments.Count != 0)
{
if (!Directory.Exists(basePath + folder.FolderPath))
{
Directory.CreateDirectory(basePath + folder.FolderPath);
}
for (int i = 1; i <= mi.Attachments.Count; i++)
{
if (fileName != null)
{
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
totalfilesize = totalfilesize + mi.Attachments[i].Size;
if (!File.Exists(basePath + mi.Attachments[i].FileName))
{
Console.WriteLine("Saving " + mi.Attachments[i].FileName);
mi.Attachments[i].SaveAsFile(basePath + mi.Attachments[i].FileName);
}
else
{
Console.WriteLine("Already saved " + mi.Attachments[i].FileName);
}
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
So it basically searches the entire "Inbox" and saves all the attachments but like I said not the one I want only - "Reports.pdf"
What am I doing wrong here?
In static void IterateMessages(Outlook.Folder folder) you currently only check for if (fileName != null) (which should never happen as fileName is always assigned at the beginning of the method).
You need to add a condition to check if the attached file meets your fileName-Criteria, e.g.:
if (mi.Attachments[i].FileName == fileName) {
//Save your attachment
} else {
// naming-critera not met, skip...
}

i am using DiffMatchPatch-Library and I want to know on which line in my file the change was found

internal void diffmatchfunc(string newtext, string oldtext)
{
diff_match_patch dmp = new diff_match_patch();
var listDiff = dmp.diff_main(newtext,oldtext,true);
dmp.diff_cleanupEfficiency(listDiff);
foreach (var diffitem in listDiff)
{
if (diffitem.operation != Operation.EQUAL)
{
if(diffitem.text == "\n" || diffitem.text == " ")
{
log.Debug("not Important");
}
else
{
log.Debug(diffitem.operation + " Ă„nderung : " + diffitem.text);
}
}
}
}
the function-call:
diffmatchfunc(File.ReadAllText("Path"), File.ReadAllText("Path...."));

While statement for downloading URL strings

I would like to ask, How I can use the While statement for downloading URL?
Here's what I want to happen.
I want to check if the url from CheckBoxListItems is already exist from my ListView
There's a case that I'm adding another urls to my listbox and I don't want to download again.
if url is already exists in my listview it will skip and proceed to the next url(which is not yet downloaded).
Here's my current codes:
int count = 0;
int total = LB.CheckedItems.Count;
string counter = string.Empty;
using (cts = new CancellationTokenSource())
{
try
{
if (cts.IsCancellationRequested) { throw new TaskCanceledException(); }
txtOutput.Text = string.Empty;
Cursor = Cursors.WaitCursor;
Parsing = true;
Text = "Getting links information. Please wait...";
foreach (string url in LB.CheckedItems)
{
var info = await Task.Run(() => Parser.GetJsonData(url, cts.Token));
count++;
counter = "( " + count + " of " + total + " )";
lblTotalLinks.Text = counter;
Text = "Parsing in progress. Please wait... " + counter;
AddToListView(info); //ADD DOWNLOADED STRINGS TO LISTVIEW
}
Text = "Parsing done. " + counter;
}
catch (OperationCanceledException ex)
{ Text = ex.Message; }
catch (Exception ex)
{ MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
Parsing = false;
Cursor = Cursors.Default;
cts = null;
//ADD TO LISTVIEW()
private void AddToListView(MediaInfo info)
{
int count = LV.Items.Count + 1;
var results = new List<ListViewItem> { new ListViewItem(new[]
{
count.ToString(),
info.Series,
"Episode " + info.Episode,
info.Title,
info.Runtime,
info.Resolution,
info.Category,
info.URL, //here's what I want to check if already exists
info.M3u8_url,
info.FileSize,
info.Fragments
})};
ListViewItem[] array = results.ToArray();
LV.BeginUpdate();
LV.ListViewItemSorter = null;
LV.Items.AddRange(array);
LV.Focus();
LV.EndUpdate();
Countlists();
LV.Items[LV.Items.Count - 1].EnsureVisible();
}
this is the example of what I want:
string urlExists = string.Empty;
foreach (ListViewItem item in LV.Items)
{
urlExists = item.SubItems[7].Text;
foreach (string url in LB.CheckedItems)
{
while (url != urlExists)
{
}
}

Replacing string on a file that are checked in list view C#

I am trying to create a program that will replace a string inside .txt file.
heres the trick. I am replacing the string in the file if they are checked,
but when I do an alternate check its still replacing the other.
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
DateTime now = DateTime.Now;
List<string> allFiles = new List<string>();
AddFileNamesToList(sourceFolder, allFiles);
if (listView1.CheckedItems.Count != 0)
{
foreach (String file in allFiles)
{
for (int x = 0; x <= listView1.CheckedItems.Count - 1; x++)
{
if (file.Contains(listView1.CheckedItems[x].Text))
{
MessageBox.Show("File contains: " + listView1.CheckedItems[x].Text);
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, Searchbar.Text, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content); writer.Close();
}
else
{
}
}
catch
{
}
}
}
}
}
}
else
{
MessageBox.Show("Please Check the files you want to rename");
}
}
public static void AddFileNamesToList(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
try
{
foreach (string fileName in fileEntries)
{
allFiles.Add(fileName);
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points"
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
AddFileNamesToList(item, allFiles);
}
}
}
I am still confused about what you are trying to do, but to simplify things, why don't you, when you populate the ListView with the files in the directory, add the file path (or a file object) to the tag property of the ListViewitem?
That way, when you loop through the checked items, you can just retrieve the file directly instead of having to loop through two Lists at once.
Something like:
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
AddFileNamesToList(sourceFolder);
if (listView1.CheckedItems.Count == 0)
{
MessageBox.Show("Please Check the files you want to rename");
return;
}
for (int x = 0; x < listView1.CheckedItems.Count; x++)
{
var file = listView1.CheckedItems[x].Tag.ToString()
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, SearchWord, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content);
writer.Close();
}
}
catch
{
}
}
}
}
Sorry for the indenting and also if this doesn't work straight as is, I haven't tested this.

listview data write onto csv file and then reading data from csv and displaying on listview

I have a form application on which multiple text boxes and list view given... I want to show list view data into csv file and then read data from csv and displayng onto listview. Code is given here... in this code m not getting desire output
private void btnUserInformation_Click(object sender, EventArgs e)
{
ListView view=new ListView();
string filepath=#"E:\Visual Studio Project\UserInfoTestApp\UserInfoTestApp\UserInfo.csv";
InformationInsertion();
ClearFields();
ListViewtoCSV(view, filepath);
}
public void ListViewtoCSV(ListView lv,string path)
{
string Info ="";
for (int i = 0; i < lv.Items.Count; i++)
{
for (int j = 1; j < lv.Items.Count; j++)
{
Info += lvUserInformation.Items[i].SubItems[j].Text + ",";
}
Info = Info.TrimEnd(',');
}
if (!File.Exists(path))
{
File.WriteAllText(path, Info);
}
File.AppendAllText(path, Info);
}
plz write simple code which can be understand easily
I hope I have understood and i coded this:
private void saveInCSVFILE()
{
if (txtName.Text != string.Empty && txtLastName.Text != string.Empty && txtAge.Text != string.Empty && txtAdress.Text != string.Empty && txtContactNumber.Text != string.Empty)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("filename.csv", true))
{ sw.WriteLine(string.Format("{0};{1};{2};{3};{4}", txtName.Text, txtLastName.Text, txtAge.Text, txtAdress.Text, txtContactNumber.Text)); }
updateTable();
}
}
private void updateTable()
{
dgv.Rows.Clear();
dgv.Columns.Clear();
using (System.IO.StreamReader sr = new System.IO.StreamReader("filename.csv"))
{
while (sr.Peek() > -1)
{
string setRow = string.Empty;
string[] tmp = sr.ReadLine().Split(';');
setRow = tmp[0] + ';' + tmp[1] + ';' + tmp[2];
dgv.Rows.Add(setRow.Split(';'));
}
}
}
1)If you want export this project never use the relative path but you must use the absolute path
2)I have used the using construct so the file will closed automatically when the loop is finished.
3)This isn't the best solution because every time that you call update table before it clear the table from column and row and after fill the dgv with the data.
Edit:
I think this is a better solution:
private void SaveInCSVFILE()
{
if (txtName.Text != string.Empty && txtLastName.Text != string.Empty && txtAge.Text != string.Empty && txtAdress.Text != string.Empty && txtContactNumber.Text != string.Empty)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("filename.csv", true))
{ sw.WriteLine(string.Format("{0};{1};{2};{3};{4}", txtName.Text, txtLastName.Text, txtAge.Text, txtAdress.Text, txtContactNumber.Text)); }
UpdateTable();
}
}
private void UpdateTable()
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("filename.csv"))
{
int tmpCountRow = 0;
while (sr.Peek() > -1)
{
tmpCountRow++;
if (tmpCountRow > this.rowCountFile)
{
AddRow(sr.ReadLine());
this.rowCountFile++;
}
else
sr.ReadLine();
}
}
}
private void ClearDataGridView()
{
dgv.Rows.Clear();
dgv.Columns.Clear();
}
private void AddRow(string s)
{
string setRow = string.Empty;
string[] tmp = s.Split(';');
setRow = tmp[0] + ';' + tmp[1] + ';' + tmp[2];
dgv.Rows.Add(setRow.Split(';'));
}
private void LoadTable()
{
ClearDataGridView();
dgv.ColumnCount = 3;
dgv.Columns[0].HeaderCell.Value = "First Name";
dgv.Columns[1].HeaderCell.Value = "Last Name";
dgv.Columns[2].HeaderCell.Value = "Age";
using (System.IO.StreamReader sr=new System.IO.StreamReader("filename.csv"))
{
while (sr.Peek() > -1)
{
this.rowCountFile++;
while (sr.Peek() > -1)
{
AddRow(sr.ReadLine());
}
}
}
}
In this second solution I' ve implemented the function LoadTable() AddRow(string s) ClearDataGrdView() and I've edited UpdateTable()
1)The method LoadTable() will call in the form_load: this method fill your datagridview(dgv) with the data that were in the csv file. And this method save the line that are in the file
2)the method AddRow(string s) simply add a row in the dgv
3)the method ClearDataGridView() is called in the LoadTable(): clear the datagridview from rows and columns that are in that moment
4)the method UpdateTable() now is better because simply add the rows that before they aren't.

Categories

Resources