remove space at the end of the line in text file - c#

I have got text file with the contents like the below
wYFgemq4-IU372t5I-J0UIIdAd-gcojGR7z BA1111111
HoSOtYLI-90yntvqB-2rV/RLiG-BT69R0NV BA1111111
h1uLXWq4-IU2QUkVr-UYuqipiT-byAuoHn7 BG2222222
jL2MFmq4-IU1VLifN-LZmFc+bu-ibc/2IJp GC1111111
zhoZpmq4-IU27lkQ1-kqNLXTbT-ec28qGPR FG1111111
but unfortunately there is one more space is adding at the end of 5th line by this I am getting an error when I upload the file ...
How can I remove the space ant the end of the fifth line (i.e)
zhoZpmq4-IU27lkQ1-kqNLXTbT-ec28qGPR FG1111111(at here)
would any one please help on this
and this is my code
private bool ParseUploadedDoc(string strUpload)
{
bool blresult = true;
strUpload = strUpload.Replace("\r","");
char [] delimitedchars = {'\n'};
string[] splitwords = strUpload.Split(delimitedchars);
string[] column;
StringBuilder InvalidCert = new StringBuilder();
StringBuilder InvalidSerial = new StringBuilder();
foreach (string word in splitwords)
{
column = word.Split('\t');
column[1].Trim();
if (column[0].Length != 35)
{
InvalidCert.Append(column[0].ToString());
InvalidCert.Append(", ");
blresult = false;
}
/// getting error at here
if (column[1].Length != 9)
{
InvalidSerial.Append(column[1].ToString());
InvalidSerial.Append(", ");
blresult = false;
}
}
if (blresult == false)
{
string strErrCert = "Invalid Certificate Id(s): " + InvalidCert.ToString();
strErrCert = strErrCert.Substring(0, strErrCert.Length - 2);
LblInvalidCert.Text = strErrCert;
string strErrFru = "Invalid Serial Number(s): " + InvalidSerial.ToString();
strErrFru = strErrFru.Substring(0, strErrFru.Length - 2);
LblInvalidFru.Text = strErrFru;
}
return blresult;
}

Problem is at this line
column[1].Trim();
you should do
column[1] = column[1].Trim();

Related

Find a word in a TextBox1 and if it found add the line to TextBox2

First I read the TextBox1 using TextReader than tried to find a string 'flag' in TextBox1
TextReader read = new System.IO.StringReader(TextBox1.Text);
int rows = 5000;
string[] text1 = new string[rows];
for (int r = 1; r < rows; r++)
{
text1[r] = read.ReadLine();
}
string flag = "healthy";
string[] readText = text1;
foreach (string s in readText)
{
if ((s.Contains(flag) == true))
{
TextBox2.Text = s.ToString();
break;
}
else
{
TextBox2.Text = "Not Found";
}
}
than I got this error []
I want the program to find a keyword in a TextBox lines if the program finds it write the keyword with the whole line into another textbox TextBox2.
I think you what to add "?" on s
to be like this:
if ((s?.Contains(flag) == true))
{
//..

Email to CSV C# - String isn't formatting correctly

So I am currently parsing emails that we receive from work, all of which are formatted almost exactly the same, and I am getting the data that I need out of all of them, however I am experiencing problems retrieving a "description", which comes in multiple lines. I've tried removing the "\n" out of these strings, but it doesn't always work. When I open the .csv files, the formatting is fine sometimes, but otherwise these extra returns in the strings ruin the entire thing.
Here is my code:
public static void Main(string[] args)
{
helper();
Console.WriteLine("Press any key to exit ... ");
Console.ReadKey();
} //end main method
public static void helper()
{
//initiate outlook
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
subFolder = inboxFolder.Folders["WorkOrders"]; //folder.Folders[1];
Console.WriteLine("Folder Name: {0}", subFolder.Name);
Console.WriteLine("Number of Emails: {0}", subFolder.Items.Count.ToString());
Console.WriteLine();
Console.WriteLine("-------------------------");
Console.WriteLine();
//Variables for loop
String sub;
String date;
String time;
String body;
String desc;
String storeNumber;
String workOrderNumber;
int indexOfDesc;
int indexOfSp;
int items = subFolder.Items.Count;
DataTable dt = new DataTable();
dt.Columns.Add("Work Order Number");
dt.Columns.Add("Date");
dt.Columns.Add("Store Number");
dt.Columns.Add("Description");
dt.Rows.Add("Work Order Number", "Date", "Store Number", "Description");
dt.Rows.Add("", "", "", ""); // just a blank row
for (int i = 1; i <= items; i++)
{
item = (Microsoft.Office.Interop.Outlook.MailItem)subFolder.Items[i];
sub = item.Subject;
date = item.SentOn.ToLongDateString();
body = item.Body;
desc = "";
storeNumber = sub.Substring(0, 5);
workOrderNumber = sub.Substring(sub.Length - 10);
indexOfDesc = body.IndexOf("Description Overview:");
indexOfSp = body.IndexOf("Safety Precautions:");
desc = body.Substring(indexOfDesc, indexOfSp - indexOfDesc);
desc = desc.Replace("\t", string.Empty);
desc = desc.Replace("\n", string.Empty);
// Add row in data table
dt.Rows.Add(workOrderNumber, date, storeNumber, desc);
// Process Date
createCSV(dt);
// *** Console Output for testing *** //
Console.WriteLine("Index: {0}", i.ToString());
Console.WriteLine("Store Number: {0}", sub.Substring(0, 5));
Console.WriteLine("Work Order Number: # " + workOrderNumber);
Console.WriteLine("Sent: {0}", date);
Console.WriteLine(desc);
Console.WriteLine();
Console.WriteLine("-------------------------");
Console.WriteLine();
}
PrintTable(dt);
}
catch (System.Runtime.InteropServices.COMException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
} //end finally
}
private static void PrintTable(DataTable dt)
{
DataTableReader dtReader = dt.CreateDataReader();
while (dtReader.Read())
{
for (int i = 0; i < dtReader.FieldCount; i++)
{
Console.Write("{0} = {1} ",
dtReader.GetName(i).Trim(),
dtReader.GetValue(i).ToString().Trim());
}
Console.WriteLine();
}
dtReader.Close();
}
/**
* createCSV(DataTable dt) takes each line from data
* table and appends it to a csv file created at the var path
* #param dt - DataTable
**/
public static void createCSV(DataTable dt)
{
String path = "C:\\Users\\WORK\\Desktop\\test.csv";
StringBuilder sb = new StringBuilder();
foreach(DataRow dr in dt.Rows){
foreach(DataColumn dc in dt.Columns){
sb.Append(FormatCSV(dr[dc.ColumnName].ToString()) + ",");
} // end foreach
sb.Remove(sb.Length-1,1); //remove comma
sb.AppendLine();
} // end foreach
File.WriteAllText(path, sb.ToString());
} // end createCSV()
public static string FormatCSV(string input)
{
try
{
if (input == null)
return string.Empty;
bool containsQuote = false;
bool containsComma = false;
int len = input.Length;
for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
{
char ch = input[i];
if (ch == '"')
containsQuote = true;
else if (ch == ',')
containsComma = true;
}
if (containsQuote && containsComma)
input = input.Replace("\"", "\"\"");
if (containsComma)
return "\"" + input + "\"";
else
return input;
}
catch
{
throw;
}
}
} //end class
And here is a screenshot of what the CSV file looks like. Mind you, all of the descriptions in the email have extra spaces and stuff in them, and I highlighted the rows that worked the way I want them too: no extra spaces, just one line of the proper information. You can see how the returns ruin the spreadsheet though.
So any help would be so greatly appreciated.
One problem when working with newlines is that sometimes it's not the standard CRLF (\r\n) that Windows uses. Sometimes it is just \r and sometimes it is just \n.
When you don't have control over the newline character it can be a decent safety net to replace all three.
var sub = string.Empty;
var foo = myString.Replace("\r\n", sub).Replace("\r", sub).Replace("\n", sub);
This fixes those cases where you are getting say
Some line item\r\n
Another line item\n
Last line item\r
Removing just \n may work just fine in one application, but another application displaying the same string may still put it on a new line.

Delete row in a CSV file and show in DataGridView using c#

I have a problem when I want to delete a row in a CSV File, I have this code but only deletes the field that contains the line.
Example:
CSV File:
ID,Name,Lastname,Country
1,David,tod,UK
2,Juan,Perez,Germ
3,Pepe,Lopez,Col
First iteration, sending the id 1 to delete the line:
ID,Name,Lastname,Country
David,tod,UK
2,Juan,Perez,Germ
3,Pepe,Lopez,Arg
Just delete the id I want, but not the whole line
The expected result would be that like this:
ID,Name,Lastname,Country
2,Juan,Perez,Arg
3,Pepe,Lopez,Col
this is my code, What am I doing wrong? I have never used csv in C# :(
string searchid = "1";
string[] values = File.ReadAllText("C:\\registros.csv").Split(new char[] { ',' });
StringBuilder ObjStringBuilder = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
if (values[i].Contains(searchid))
continue;
ObjStringBuilder.Append(values[i] + ",");
}
ObjStringBuilder.ToString().Remove(ObjStringBuilder.Length - 1);
File.WriteAllText("\\registros.csv", ObjStringBuilder.ToString());
Another question is how can I show the CSV file in a datagridview in Windows Forms. I have this logic, don't know if this is correct, but how I can show it?
public DataTable ConvertCSVtoDataTable()
{
StreamReader sr = new StreamReader("\\registros.csv");
string[] headers = sr.ReadLine().Split(',');
DataTable dt = new DataTable();
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
dt.Rows.Add(dr);
}
return dt;
}
Thanks!
You can delete row from CSV using below link
Delete rows from CSV
and
You can convert the CSV into DataTable using the below code. If your csv file uses delimiter as ,
public DataTable ReadCSV(String FilePath, Boolean IsHeader)
{
string strConn = null;
string folderpath = null;
try
{
folderpath = FilePath.Substring(0, FilePath.LastIndexOf("\\") + 1);
string FileName = Path.GetFileName(FilePath);
if (IsHeader == true)
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + folderpath + ";" + "Extended Properties=\"text;HDR=YES\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + folderpath + ";" + "Extended Properties=\"text;HDR=NO\"";
}
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = strConn;
Conn.Open();
string s1 = "select * from [" + FileName + "]";
OleDbDataAdapter da1 = new OleDbDataAdapter(s1, Conn);
DataSet dtall = new DataSet();
da1.Fill(dtall);
Conn.Close();
return dtall.Tables[0].Copy();
}
catch (Exception ex)
{
Exception excep = new Exception("CSV : " + ex.Message);
throw excep;
}
}
Reading and writing CSV files is not as trivial as it first seems. Cells can have embedded commas, and even new line characters. The following is one implementation of a CSV reader which can optionally be run asynchronously as a background worker. This implementation returns a standard DataTable which can easily be bound to a DataGridView:
grid.DataSource = dataTable;
The CsvReader class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace CsvReaderExample
{
public class CsvReader
: BackgroundWorker
{
string[] m_lines;
public DataTable DataTable { get; private set; }
public CsvReader(string[] lines)
{
m_lines = lines;
WorkerReportsProgress = true;
WorkerSupportsCancellation = true;
}
public DataTable RunWorker()
{
return DataTable = ParseCsvLines();
}
protected override void OnDoWork(DoWorkEventArgs e)
{
base.OnDoWork(e);
e.Result = DataTable = ParseCsvLines();
}
private DataTable ParseCsvLines()
{
if (m_lines.Length == 0)
return null;
var table = new DataTable();
var columns = table.Columns;
var columnNames = GetRowValues(m_lines[0]);
foreach (var columnName in columnNames)
{
var name = columnName;
int number = 2;
while (columns.Contains(name))
name += " " + number++;
columns.Add(name);
}
var rows = table.Rows;
for (int index = 1, linesCount = m_lines.Length; index < linesCount; index++)
{
if (CancellationPending)
return null;
var line = m_lines[index];
var values = GetRowValues(line);
int valueCount = values.Count;
if (valueCount > columns.Count)
{
int columnNumber = columns.Count;
while (columns.Contains(columnNumber.ToString()))
columnNumber++;
columns.Add(columnNumber.ToString());
}
rows.Add(values.ToArray());
if (WorkerReportsProgress)
ReportProgress(100 * index / linesCount);
}
return table;
}
const char COMMA = ',',
DOUBLE_QUOTE = '"',
VERTICAL_BAR = '|';
private List<string> GetRowValues(string line)
{
var builder = new StringBuilder();
var values = new List<string>();
var inDoubleQuotes = false;
var maxIndex = line.Length - 1;
for (int index = 0; index <= maxIndex; index++)
{
char c = line[index];
if (c == DOUBLE_QUOTE)
{
if (index == 0)
{
inDoubleQuotes = true;
continue;
}
if (index < maxIndex)
{
var nextIndex = index + 1;
if (nextIndex < maxIndex)
{
if (line[nextIndex] == DOUBLE_QUOTE)
{
index++;
if (inDoubleQuotes)
builder.Append(DOUBLE_QUOTE);
continue;
}
}
}
inDoubleQuotes = !inDoubleQuotes;
continue;
}
if (c == COMMA)
{
if (inDoubleQuotes)
{
builder.Append(c);
continue;
}
values.Add(builder.ToString());
builder = new StringBuilder();
continue;
}
builder.Append(c);
}
values.Add(builder.ToString());
return values;
}
#region Sanitise cells with new line characters
public static void SanitiseCellsWithNewLineCharacters(string fileName)
{
var text = File.ReadAllText(fileName, Encoding.Default);
text = text.Replace("\r\n", "\n");
text = text.Replace("\r", "\n");
using (var writer = File.CreateText(fileName))
{
var inDoubleQuotes = false;
foreach (char c in text)
{
if (c == '\n' && inDoubleQuotes)
{
writer.Write(VERTICAL_BAR);
continue;
}
if (c == DOUBLE_QUOTE)
{
if (inDoubleQuotes)
inDoubleQuotes = false;
else
inDoubleQuotes = true;
}
writer.Write(c);
}
}
}
#endregion
}
}
You can read the DataTable synchronously as follows:
var lines = File.ReadAllLines("C:\\registros.csv");
var csvReader = new CsvReader(lines);
var dataTable = csvReader.RunWorker();
You could then remove row(s) from the DataTable with a method such as:
private static void RemoveById(DataTable dataTable, int id)
{
var column = dataTable.Columns["ID"];
if (column == null)
return;
var rows = dataTable.Rows;
for (int index = rows.Count - 1; index >= 0; index--)
{
var row = rows[index];
var value = row ["ID"];
if (value == null)
continue;
if (value.Equals(id))
{
rows.RemoveAt(index);
return;
}
}
}
Call it:
RemoveById(dataTable, 1);
The first thing that is wrong with your implementation is that you use ',' as the separator. You should either split on the new-line character '\n' or read the file line by line as follows:
var lines = new List<string>();
var file = new System.IO.StreamReader("c:\\registros.csv");
string line;
while((line = file.ReadLine()) != null)
{
lines.Add(line);
}
file.Close();
You could then look for the line that starts with the id you are looking for. When you find it, remove the line from the list.
for(int i=0; i++; i<lines.Count)
{
if (lines[i].StartsWith(searchid))
{
lines.RemoveAt(i);
break;
}
}
Next step is to write the result back to the file:
File.WriteAllLines("c:\\registros.csv", lines);
Regarding your second question, I found a similar Q/A on stackoverflow here.
First step is creating the DataTable, then you'll have to bind the table to the table control that will show the data.
SIMPLE & UNDERSTANDABLE!`
Solution For your First Problem is:
****Reading & Writing back to CSV File!****
string searchid = "1";
string[] values = File.ReadAllText(#"Complete Path Of File").Split(new char[] { '\n' });
StringBuilder ObjStringBuilder = new StringBuilder();
for (int i = 0; i < values.Length - 1; i++)
{
if (values[i].StartsWith(searchid) == false)
{
ObjStringBuilder.Append(values[i]+"\n");
}
}
File.WriteAllText(#"Complete Path Of File", ObjStringBuilder.ToString());
}
Answer to your Second Doubt:
****Populating DataGridView dynamically from CSV File!****
Comma(,) Problem SOLVED:
DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(#"..\\Book1.csv");
if (fileContent.Count() > 0)
{
//Create data table columns dynamically
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add(columns[i]);
}
//Add row data dynamically
for (int i = 1; i < fileContent.Count(); i++)
{
string[] rowData = fileContent[i].Split(',');
string[] realRowData = new string[columns.Count()];
StringBuilder collaboration = new StringBuilder();
int v = 0;
//this region solves the problem of a cell containing ",".
#region CommaSepProblem
for (int j = 0, K = 0; j < rowData.Count(); j++, K++)
{
//After splitting the line with commas. The cells containing commas will also be splitted.
//Fact: if a cell contains special symbol in excel that cell will be saved in .csv contained in quotes E.g A+B will be saved "A+B" or A,B will be saved as "A,B"
//Our code splits everything where comma is found. So solution is:
//Logic: After splitting if a string contains even number of DoubleQuote then its perfect cell otherwise, it is splitted in multiple cells of array.
if ((rowData[j].Count(x => x == '"') % 2 == 0))//checks if the string contains even number of DoubleQuotes
{
realRowData[K] = quotesLogic((rowData[j]));
}
else if ((rowData[j].Count(x => x == '"') % 2 != 0))//If Number of DoubleQuotes are ODD
{
int c = rowData[j].Count(x => x == '"');
v = j;
while (c % 2 != 0)//Go through all the next array cell till it makes EVEN Number of DoubleQuotes.
{
collaboration.Append(rowData[j] + ",");
j++;
c += rowData[j].Count(x => x == '"');
}
collaboration.Append(rowData[j]);
realRowData[K] = quotesLogic(collaboration.ToString());
}
else { continue; }
}
#endregion
dtDataSource.Rows.Add(realRowData);
}
if (dtDataSource != null)
{
dataGrid1.ItemsSource = dtDataSource.DefaultView;
}
}
Add This Method Too:
string quotesLogic(string collaboration)
{
StringBuilder after = new StringBuilder(collaboration);
if (after.ToString().StartsWith("\"") && after.ToString().EndsWith("\""))//removes 1st and last quotes as those are system generated
{
after.Remove(0, 1);
after.Remove(after.Length - 1, 1);
int count = after.Length - 1;
//FACT: if you try to add DoubleQuote in a cell in excel. It'll save that quote as 2 times DoubleQuote(Like "") which means first DoubleQuote is to give instruction to CPU that the next DoubleQuote is not system generated.
while (count > 0)//This loop find twice insertion of 2 DoubleQuotes and neutralise them to One DoubleQuote.
{
if (after[count] == '"' && after[count - 1] == '"')
{
after.Remove(count, 1);
}
count--;
}
}
return after.ToString();
}

New line in C# for Word Document

how to recognize new line c# while uploading word documents..? i have to give next line as a new word in word document here what is happening means if i add three or more words in .doc in separate line its taking as one word i want to separate the words but if i give a space after a word it is taking as expected without giving space if i start a new word in new line its taking as one word
money
power
cash
moneypowercash
like this iam getting here if i give space after these words its getting as expected
how to resolve this issue here i will give my code to generating this keyword
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (cmbDepartment.SelectedValue != "0" && cmbDocumentType.SelectedValue != "0")
{
TodayDate = DateTime.Today.ToString("yyyy-MM-dd");
TempFolder = System.Configuration.ConfigurationManager.AppSettings["TempWorkFolder"];
TextReader reader = new FilterReader(TempFolder + Session["EncyptImgName"]);
StringBuilder Keywords = new StringBuilder();
using (reader)
{
Keywords = Keywords.Append(reader.ReadToEnd());
}
//remove common words
string[] removablewords = { ":", ".", "~"};
foreach (string st in removablewords)
{
Keywords.Replace(st, " ");
}
//Reomve unwated spaces
while (Keywords.ToString().Contains(" "))
{
Keywords.Replace(" ", " ");
}
string str = Keywords.ToString();
Keywords.Clear();
Keywords.Append("<words><s>" + str.Replace(" ", "</s><s>") + "</s></words>");
string xml = Keywords.ToString();
XElement items = XElement.Parse(xml);
var groups = from t in items.Descendants("s")
group t by t.Value.ToLower() into g
select new KeyFrequency(g.Key, g.Count());
groups = groups.OrderByDescending(g => g.Frequency).Take(15);
keyvalues = new List<string>();
foreach (KeyFrequency g in groups)
{
keyvalues.Add(g.Key);
}
for (key = 0; key < keyvalues.Count && key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = true;
btn.Text = keyvalues[key];
btn.CommandArgument = keyvalues[key];
}
if (key < 10)
{
for (key = key; key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = false;
}
}
else
{
AsyncFileUpload1.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
Button1.Text = "Keywords Not Available for This Document";
Button1.CommandArgument = null;
Button2.Visible = false;
Button3.Visible = false;
Button4.Visible = false;
Button5.Visible = false;
Button6.Visible = false;
Button7.Visible = false;
Button8.Visible = false;
Button9.Visible = false;
Button10.Visible = false;
}
}
For each new line, try replacing \n with "</w:t><w:br/><w:t>". It worked for me.
string.Replace("\n", "</w:t><w:br/><w:t>")

using .replace to replace a word in text document (c#)

currently have the following code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
userPasswordPair[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
}
}
}
the text file is set out as: 'username' 'password
what i'm trying to do is be able to edit the password and replace it with a new one using my code, but my code seems to do nothing and the text file just stays the same.
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
// set the new password in the same list and save the file
fileLineString[i] = Session["user"].ToString() + " " + newPasswordTextBox.Text;
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt"), fileLineString);
break; // exit from the for loop
}
}
At the moment, you're not storing the file.
Your replace is not assigned to a variable (Replace does not edit or write anything, it just returns the new string object).
Corrected code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
fileLineString[i] = fileLineString[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
break;
}
}
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt", fileLineString);
String _userName = "User";
String _newPassword = "Password";
// Reading All line from file
String _fileContent = System.IO.File.ReadAllLines("filePath").ToString();
// Pattern which user password like to changed
string _regPettern = String.Format(#"{0} ?(?<pwd>\w+)[\s\S]*?", _userName);
Regex _regex2 = new Regex(_regPettern, RegexOptions.IgnoreCase);
String _outPut = Regex.Replace(_fileContent, _regPettern, m => m.Groups[1] + " " + _newPassword);
// Writing to file file
System.IO.File.WriteAllText("filePath", _outPut);

Categories

Resources