native message response extension chrome - c#

I use this code
// background.js
chrome.runtime.sendNativeMessage( "com.example.native",
{ text: "test" },
function(response) {
console.log("Received " + response);
});
C# code
private static void OpenStandardStreamOut(string stringData)
{
string msgdata = "{\"text\":\"" + stringData + "\"}";
int DataLength = msgdata.Length;
Stream stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((DataLength >> 0) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 8) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 16) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 24) & 0xFF));
Console.Write(msgdata);
}
private static List<LoginPack> OpenStandardStreamIn()
{
Stream stdin = Console.OpenStandardInput();
int length = 0;
byte[] bytes = new byte[4];
stdin.Read(bytes, 0, 4);
length = System.BitConverter.ToInt32(bytes, 0);
string input = "";
for (int i = 0; i < length; i++)
{
input += (char)stdin.ReadByte();
}
JObject Read=(JObject)JsonConvert.DeserializeObject<JObject>(input);
//string dataPackStr = JsonConvert.SerializeObject(Read);
Chrome chromeClass = new Chrome();
List<LoginPack> lp = new List<LoginPack>();
if (Read!=null)
if (Read.Count != 0)
lp = chromeClass.getInfoFromChrome(Read["text"].ToString());
if (lp.Count == 0)
return null;
return lp;
}
//class chrome
public class Chrome
{
public class Data
{
public string key { get; set; }
public string value { get; set; }
}
public List<LoginPack> getInfoFromChrome(string colName)
{
try
{
// string filename = "my_chrome_passwords.html";
// StreamWriter Writer = new StreamWriter(filename, false, Encoding.UTF8);
string db_way = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
+ "/Google/Chrome/User Data/Profile 1/Login Data1";
Console.WriteLine("DB file = " + db_way);
string db_field = "logins";
List<LoginPack> lp = new List<LoginPack>();
byte[] entropy = null;
string description;
string ConnectionString = "data source=" + db_way + ";New=True;UseUTF16Encoding=True";
DataTable DB = new DataTable();
string sql = string.Format("SELECT * FROM {0} where action_url=\"{1}\" or origin_url=\"{2}\"", db_field, colName, colName);
// System.IO.StreamWriter file1 = new System.IO.StreamWriter("c:\\test.txt");
// file1.WriteLine(sql);
// file1.Close();
using (SQLiteConnection connect = new SQLiteConnection(ConnectionString))
{
SQLiteCommand command = new SQLiteCommand(sql, connect);
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
adapter.Fill(DB);
int rows = DB.Rows.Count;
for (int i = 0; i < rows; i++)
{
byte[] byteArray = (byte[])DB.Rows[i][5];
byte[] decrypted = DPAPI.Decrypt(byteArray, entropy, out description);
lp.Add(new LoginPack { userNameElement = (string)DB.Rows[i][2], userName = (string)DB.Rows[i][3], passElement = (string)DB.Rows[i][4], pass = new UTF8Encoding(true).GetString(decrypted) });
//System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
//file.WriteLine(lp[i].userName);
//file.Close();
}
}
// Writer.Close();
return lp;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ex = ex.InnerException;
return null;
}
}
}
Application(C#) give data from extension but Extension cant get any response from app
if I use OpenStandardStreamOut function at first(in C# app) then Extension can get response from it
what's the problem?

I think your 'Chrome' class is working badly. Check that again and make sure to use Standard Streams instead of your third party Streams. Also remove Console.WriteLine("DB file = " + db_way); line and try again.

Related

How to encode QR with TLV values in C#

I have this code in C# which use it to generate a QR code base64 and want to decode the output into original TLV values as strings, for example in my code I am generating the QR code encode base64 and want to get back with original TLVs tags and store it in separate string per each value
using System;
namespace tlvgenerator
{
class Program
{
static void Main(string[] args)
{
string Name = GetHexString(1, Encoding.UTF8.GetBytes("Name")); //Tag1
string Serial = GetHexString(2, Encoding.UTF8.GetBytes("123456789123456789")); //Tag2
string dateTimeStr = GetHexString(3, Encoding.UTF8.GetBytes("2022-07-17T11:20:51Z")); //Tag3
string ModelNum = GetHexString(4, Encoding.UTF8.GetBytes("12356.123")); //Tag4
string PartNo = GetHexString(5, Encoding.UTF8.GetBytes("9782.45")); //Tag5
string SN = GetHexString(6, Encoding.UTF8.GetBytes("abcdef12345"));//Tag6
string Shelf = GetHexString(7, Encoding.UTF8.GetBytes("A2F345"));//Tag6
string Area = GetHexString(8, Convert.FromBase64String(Area)); //Tag7
string Building = GetHexString(9, Convert.FromBase64String(Building)); //Tag8
string decString = Name + Serial + dateTimeStr + ModelNum + PartNo + SN + Shelf + Area + Building;
string finalQR = HexToBase64(decString);
Console.WriteLine(finalQR);
}
static string GetHexString(int tagNo, byte[] tagValue)
{
string strTagNo = string.Format("0{0:X}", tagNo);
string tagNoVal = strTagNo.Substring(strTagNo.Length - 2, 2);
string strTagValueLength = string.Format("0{0:X}", tagValue.Length);
string tagValueLengthVal = strTagValueLength.Substring(strTagValueLength.Length - 2, 2);
return tagNoVal + tagValueLengthVal + BitConverter.ToString(tagValue).Replace("-", "");
}
static string gethexDec(Int32 TagValue)
{
string hxint = String.Format("0{0:X}", TagValue);
return hxint.Substring(hxint.Length - 2, 2);
}
public static string HexToBase64(string strInput)
{
try
{
var bytes = new byte[strInput.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(strInput.Substring(i * 2, 2), 16);
}
return Convert.ToBase64String(bytes);
}
catch (Exception)
{
return "-1";
}
}
}
}

How to retrieve attachments from Gmail message Json [duplicate]

How can I browse the email and download all attachments ?
public string Connect_Email ()
{
string Res = "";
try
{
mailclient = new TcpClient("pop.orange.fr", Convert.ToInt16("110"));
}
catch ( SocketException ExTrhown )
{
Res = "Unable to connect to server 1";
throw new Exception(ExTrhown.Message + "Unable to connect to server 1");
}
ns = mailclient.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
response = sr.ReadLine(); //Get opening POP3 banner
sw.WriteLine("USER " + "xxxxx#orange.fr"); //Send username
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 4) == "-ERR" )
{
Res = "Unable to log into server 2";
}
sw.WriteLine("PASS " + "xxxxx"); //Send password
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 3) == "-ER" )
{
Res = "Unable to log into server 3";
}
return Res;
}
public void Get_Attacht ()
{
string ClientName = "";
#region Chercher Attachment
sw.WriteLine("STAT"); //Send stat command to get number of messages
sw.Flush();
response = sr.ReadLine();
//find number of message
string[] nummess = response.Split(' ');
totmessages = Convert.ToInt16(nummess[1]);
//read emails
for ( int i = 1; i <= totmessages; i++ )
{
msg = null;
sw.WriteLine("top " + i + " 0"); //read header of each message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
//read attachment
attachment = null;
if ( Regex.Match(msg, "multipart/mixed").Success )
{
msg = null;
sw.WriteLine("retr " + i.ToString()); //Retrieve entire message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
int End = msg.IndexOf(".csv");
string LeFile = msg.Substring(End - 9, 9);
if ( Regex.Match(msg, LeFile + ".csv").Success )
{
data = msg.Split('\r');
startindex = 0;
index = 0;
lastindex = 0;
x = null;
ms = null;
fs = null;
while ( true )
{
attachment = null;
while ( !Regex.Match(data[index].Trim(), "filename").Success )
{
index++;
}
if ( index == data.Length - 1 ) break;
FileName_Email = data[index].Trim().Substring(42).Replace("\"", "");
//find start of attachment data
index++;
while ( data[index].Length != 1 )
{
index++;
}
if ( index == data.Length - 1 ) break;
startindex = index + 1;
//find end of data
index = startindex + 1;
while ( ( !Regex.Match(data[index].Trim(), "--0").Success ) && ( data[index].Length != 1 ) && ( index < data.Length - 1 ) )
{
index++;
}
if ( index == data.Length ) break;
lastindex = index - 2;
for ( int j = startindex; j <= lastindex; j++ )
{
attachment = attachment + data[j];
}
attachment = attachment + "\r\n";
if ( Regex.Match(FileName_Email.ToLower(), "csv").Success )
{
byte[] filebytes = Convert.FromBase64String(attachment);
FileStream LeFS = new FileStream(filePath + "\\testDEC.csv", FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
break;
}
}
}
}
}
sw.WriteLine("quit"); //quit
sw.Flush();
#endregion
}
It does not work, have you another simple idea ?
Try something like this
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("server");
pop3.UseBestLogin("user", "password");
foreach (string uid in pop3.GetAll())
{
IMail email = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine(email.Subject);
// save all attachments to disk
email.Attachments.ForEach(mime => mime.Save(mime.SafeFileName));
}
pop3.Close();
}
// here is a reference link you can use as well
Getting Email Attachments
If you're trying to read e-mail via POP3, I would recommend using the OpenPOP.NET library instead of rolling your own. It's pretty easy to use.
Thanks you all for your contribution. Finally I use POP3:
public string Connect_Email()
{
string Res = "";
try
{
Pop3Client email = new Pop3Client("login", "password", "server");
email.OpenInbox();
while (email.NextEmail())
{
if (email.IsMultipart)
{
IEnumerator enumerator = email.MultipartEnumerator;
while (enumerator.MoveNext())
{
Pop3Component multipart = (Pop3Component)
enumerator.Current;
if (multipart.IsBody)
{
//Console.WriteLine("Multipart body:" + multipart.Name);
}
else
{
//Console.WriteLine("Attachment name=" + multipart.Name); // ... etc
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
}
}
}
}
email.CloseConnection();
}
catch (Pop3LoginException)
{
Res = "Vous semblez avoir un problème de connexion!";
}
return Res;
}
It work well, but still I have to find and download the attachement my self.
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
This not work more. Use Modern Authentication with Microsoft.Graph after create a cliente secret into AZURE and registered tha application them.

Problem with Sign PDF by SHA1 when use iTextSharp

I have a digital signature problem with PDF files, the process is as follows:
- I have a PDF file on the Server, then I locate the signature and convert it to byte format [] with SHA1.
- The client will retrieve the signature from the USB token to assign to byte [] transmitted from the server.
- I then returned the server to assign the signature.
But when I code as below, the program still runs normally without error, but the USB signature contents are not signed into the pdf file. Please help me to fix it.
private void Form1_Load(object sender, EventArgs e)
{
string UnsingnedPdf = #"E:\PrintContractAdviceNote.pdf";
string TempPdf = #"E:\PrintContractAdviceNote_TMP.pdf";
string singnedPdf = #"E:\PrintContractAdviceNote_Sign.pdf";
PDFSigning cl = new PDFSigning();
cl.GetBytesToSign(UnsingnedPdf, TempPdf, singnedPdf, "CHUKY1", 3, "BIG BEAR");
}
public static X509Certificate2 selectCert()
{
X509Certificate2 certificate = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
if (store.Certificates.Count == 1)
{
//Return the certificate present.
certificate = store.Certificates[0];
}
else if (store.Certificates.Count > 0)
{
// Request the user to select a certificate
try
{
var certificates = X509Certificate2UI.SelectFromCollection(store.Certificates,
"Digital Certificates", "Select a certificate from the following list:",
X509SelectionFlag.SingleSelection);
// Check if one has been returned
if (certificates.Count == 1)
{
certificate = certificates[0];
var newCert = new X509Certificate2(certificate.RawData, "mypassword");
}
else
{
throw new ArgumentException("Please select a certificate to publish PnL to Flash");
}
}
catch (Exception ex)
{
}
}
else
{
throw new ArgumentException("There is no certificate available to publish PnL to flash, please contact support.");
}
}
finally
{
store.Close();
}
return certificate;
}
public class IpInfo
{
//country
public string Country { get; set; }
}
public byte[] GetBytesToSign(string unsignedPdf, string tempPdf, string signedPdf, string signatureFieldName, Int16 iType, string SignName)
{
if (File.Exists(tempPdf))
File.Delete(tempPdf);
if (File.Exists(signedPdf))
File.Delete(signedPdf);
byte[] array = null;
bool Islock = true;
FileStream os = File.OpenWrite(tempPdf);
PdfReader reader = new PdfReader(unsignedPdf);
DateTime dt = DateTime.Now;
using (PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'))
{
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.Contact = "www.marico.com";
appearance.SignDate = dt;
//BaseFont bf = BaseFont.CreateFont(HttpContent.Current.Server.MapPath("~/Resources/Font/arial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//Font font = new Font(bf, 8);
//appearance.Layer2Font = font;
appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
appearance.Acro6Layers = true;
appearance.Layer2Text = "Signed by:" + Environment.NewLine + " " + SignName + Environment.NewLine + "Date :" + Environment.NewLine + " " + dt.ToShortDateString() + " " + dt.ToShortTimeString();
Image img;
if (iType == 3)
{
img = Image.GetInstance(#"E:\Tài liệu\Marico\HINH ANH\talent.png");
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(15, 50, 235, 95), reader.NumberOfPages, signatureFieldName);
}
else
{
img = Image.GetInstance(#"E:\Tài liệu\Marico\HINH ANH\talent.png");
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(350, 50, 570, 95), reader.NumberOfPages, signatureFieldName);
}
appearance.SignatureGraphic = img;
IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
MakeSignature.SignExternalContainer(appearance, external, 8192);
array = SHA1.Create().ComputeHash(appearance.GetRangeStream());
stamper.Dispose();
stamper.Close();
}
if (iType != 3)
{
while (Islock)
{
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
Islock = IsFileLocked(unsignedPdf);
}
}
else
{
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
}
X509Certificate2 cert = selectCert();
RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(cert.PrivateKey);
formatter.SetHashAlgorithm("SHA1");
byte[] signature = formatter.CreateSignature(array);
EmbedSignature(tempPdf, signedPdf, signatureFieldName, signature);
return (array);
}
public static bool IsFileLocked(string pathfile)
{
try
{
using (FileStream fs = new FileStream(pathfile, FileMode.Open))
{
fs.Dispose();
fs.Close();
}
return false;
}
catch (IOException ex)
{
return true;
}
}
private static void SetSigPosition(PdfSignatureAppearance sigAppearance, int oldSigCount, string signatureFieldName, int numpage = 1)
{
float llx = (200 + 20) * (oldSigCount % 5) + 20,
lly = (25 + 20) * (oldSigCount / 5) + 5,
urx = llx + 200,
ury = lly + 45;
}
public void EmbedSignature(string tempPdf, string signedPdf, string signatureFieldName, byte[] signedBytes)
{
IExternalSignatureContainer external = new MyExternalSignatureContainer(signedBytes);
using (FileStream os = File.OpenWrite(signedPdf))
{
using (PdfReader reader = new PdfReader(tempPdf))
{
MakeSignature.SignDeferred(reader, signatureFieldName, os, external);
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
}
}
}
private class MyExternalSignatureContainer : IExternalSignatureContainer
{
private readonly byte[] signedBytes;
public MyExternalSignatureContainer(byte[] signedBytes)
{
this.signedBytes = signedBytes;
}
public byte[] Sign(Stream data)
{
return signedBytes;
}
public void ModifySigningDictionary(PdfDictionary signDic)
{
}
}

How to do unit test on a method that has StreamReader and Database access

I have never done unit tests before. I'd like to learn how to do it. I'd like to use Visual Studio unit test and moq.
My project is transferring data from interbase to SQL Server. Firstly, I extract data from interbase into a plain text file. The layout is FieldName + some spaces up to 32 char length + field value. Then, I write a method that reads the text file line by line; once it reaches the next record, it inserts the current record into SQL Server.
So it involves in stream reader and SQL database insertion. For the stream reader, I read some post on the Internet and I pass the Stream reader as the method's parameter; but the SQL Server part, I have no idea how to simplify my method so that it can be tested.
I really need your help.
public partial class TableTransfer
{
#region declare vars
public string FirstFldName = "";
public string ErrorMsg = "";
public List<MemoBlobTrio> MemoBlobs = null;
public string SqlServerTableName = "";
#endregion
public bool DoTransfer(System.IO.StreamReader sr, Func<TransferShare, string, string, bool> TransferTable)
{
#region declare var
bool DoInsert = true;
TransferShare transferShare = null;
string line = string.Empty;
string blobLines = string.Empty;
string fldName = string.Empty;
string value = string.Empty;
bool Is1stLine = true;
bool isMemoFld = false;
MemoBlobTrio memoBlobTrio = null;
int idx = 0;
#endregion
try
{
using(sr)
{
transferShare = new TransferShare();
ConnectSQLServer(transferShare);
transferShare.StartInsert(SqlServerTableName);
bool readNext = true;
do
{
try
{
if (readNext)
line = sr.ReadLine();
if ((line != null) && (line.Trim() != ""))
{
fldName = line.Length > 30 ? line.Substring(0, 31).TrimEnd() : "";
Is1stLine = fldName == FirstFldName;
if (Is1stLine)
{
if (DoInsert)
EndInsert(transferShare, line);
else
transferShare.ClearSQL();
DoInsert = true;
}
idx = 0;
isMemoFld = false;
while (idx < MemoBlobs.Count)
{
if (fldName == (MemoBlobs[idx] as MemoBlobTrio).fbFldName)
{
memoBlobTrio = MemoBlobs[idx] as MemoBlobTrio;
line = InsertMemoBlob(transferShare, sr, memoBlobTrio.ssFldName, fldName, memoBlobTrio.fbNextFldName);
readNext = false;
isMemoFld = true;
}
idx++;
}
if (!isMemoFld)
{
if (line.Length > 31)
value = line.Remove(0, 31);
else
value = "";
if (!TransferTable(transferShare, fldName, value))
DoInsert = false;
readNext = true;
}
}
}
catch (Exception err)
{
HandleError(err, line);
}
} while (line != null);
if (DoInsert)
EndInsert(transferShare, line);
}
}
finally
{
transferShare.SQLConn.Dispose();
}
return true;
}
private static void ConnectSQLServer(TransferShare transferShare)
{
TransferShare.SQLServerConnStr = "Data Source=" + Environment.MachineName + "\\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True";
transferShare.SQLConn.ConnectionString = TransferShare.SQLServerConnStr;
transferShare.SQLConn.Open();
}
}
public class TransferShare
{
public void StartInsert(string TableName)
{
tableName = TableName;
}
public void EndInsert(TransferShare transferShare, string line)
{
SqlCommand Cmd = null;
try
{
sqlInsFld = sqlInsFld.Remove(sqlInsFld.Length - 1);
sqlInsValue = sqlInsValue.Remove(sqlInsValue.Length - 1);
sqlInsFld = "Insert into " + tableName + " (" + sqlInsFld + ")";
sqlInsValue = " Values (" + sqlInsValue + ")";
Cmd = new SqlCommand(sqlInsFld + sqlInsValue, SQLConn);
Cmd.ExecuteNonQuery();
}
catch (Exception err)
{
throw (new Exception(err.Message));
}
finally
{
sqlInsFld = "";
sqlInsValue = "";
}
}
}

Modify/replace Text in tab-base text file in C#

This question is a continuation of a past discussion HERE. So now I managed to read every line in my text file and also read the exact string in a certain column. My issue now is that I wish to modify a text value in say Column (4) of the tab-base file with another string value.
For example, the original file is like this:
ID1 25 800 Low
ID2 25 700 Low
ID3 25 600 Low
I want to Change to:
ID1 25 800 High
ID2 25 700 High
ID3 25 600 High
… here is my full code. I appreciate your help.
string route = #"C:\MyFile.txt";
FileStream fileStream2 = new FileStream(route, FileMode.Open);
var m_readFile2 = new StreamReader(fileStream2);
var m_writeFile2 = new StreamWriter(fileStream2);
string[] colArr1 = new string[100];
string[] colArr2 = new string[100];
string[] colArr3 = new string[100];
string[] colArr4 = new string[100];
int arrcount = 1;
while ((line = m_readFile2.ReadLine()) != null)
{
string col1 = "";
string col2 = "";
string col3 = "";
string col4 = "";
col1 = line.Split('\t')[0];
col2 = line.Split('\t')[1];
col3 = line.Split('\t')[2];
col4 = line.Split('\t')[3];
colArr1[arrcount] = col1;
colArr2[arrcount] = col2;
colArr3[arrcount] = col3;
colArr4[arrcount] = col4;
m_writeFile2.WriteLine("Serv" + arrcount + "\t" + "25" + "\t" + "400" + "\t" + "High");
arrcount = arrcount + 1;
KISS
string text = File.ReadAllText(route);
text = text.Replace("Low", "High");
File.WriteAllText(route, text);
I would suggest you split the lines into an array and put a new line back together:
string source = #"D:\MyFile.txt";
string destination = #"D:\MyFile2.txt";
int columnToChange = 3;
string newValueForColumn = "High";
using (FileStream sourceStream = new FileStream(source, FileMode.Open))
{
using (FileStream destinationStream = new FileStream(destination, FileMode.CreateNew))
{
using (StreamReader sourceReader = new StreamReader(sourceStream))
{
using (StreamWriter destinationWriter = new StreamWriter(destinationStream))
{
string oldLine = string.Empty;
while ((oldLine = sourceReader.ReadLine()) != null)
{
string[] values = oldLine.Split('\t');
StringBuilder newLine = new StringBuilder();
if (values.Length > columnToChange)
{
values[columnToChange] = newValueForColumn;
for (int i = 0; i < values.Length; i++)
{
newLine.Append(values[i]);
if (i + 1 < values.Length)
{
newLine.Append('\t');
}
}
}
else
{
newLine.Append(oldLine);
}
destinationWriter.WriteLine(newLine.ToString());
}
}
}
}
}
// File.Delete(source);
File.Move(source, source + ".bak");
File.Move(destination, source);
}
//Works fine Thomas Voß - I've just added a line to ensure that Column Header is
//also not changed
string source = #"D:\MyFile.txt";
string destination = #"D:\MyFile2.txt";
int columnToChange = 3;
string newValueForColumn = "High";
using (FileStream sourceStream = new FileStream(source, FileMode.Open))
{
using (FileStream destinationStream = new FileStream(destination, FileMode.CreateNew))
{
using (StreamReader sourceReader = new StreamReader(sourceStream))
{
using (StreamWriter destinationWriter = new StreamWriter(destinationStream))
{
string oldLine = string.Empty;
while ((oldLine = sourceReader.ReadLine()) != null)
{
string[] values = oldLine.Split('\t');
StringBuilder newLine = new StringBuilder();
if (values.Length > columnToChange)
{
if (values[columnToChange] != "ColumnHeaderName")
{
values[columnToChange] = newValueForColumn;
}
for (int i = 0; i < values.Length; i++)
{
newLine.Append(values[i]);
if (i + 1 < values.Length)
{
newLine.Append('\t');
}
}
}
else
{
newLine.Append(oldLine);
}
destinationWriter.WriteLine(newLine.ToString());
}
}
}
}
}
// File.Delete(source);
File.Move(source, source + ".bak");
File.Move(destination, source);
}

Categories