How do I append only updated texts? - c#

I have a Winform control to write notes whose contents are periodically uploaded to the server.
I need to create a local file as a backup to save the contents of the notes.
When I type text into the notebox, the content remains in the note box and gets saved into the local text file. However, when I enter more texts to the note-box, the previous content as well as the new content gets appended to the local file.
How do I make sure that only the recent content gets appended to the local file? If i clear the note-box content, no content gets logged on to the server.
private void btnNote_Click(object sender, EventArgs e)
{
Note noteFrm = new Note();
//set Note Text
noteFrm.NoteText = _timeCard.NoteText;
if (noteFrm.ShowDialog() == DialogResult.OK)
{
//Save notes locally as well
string path = #"C:\QB Notes\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string projname = this._timeCard.Project.ProjectName.TrimEnd()+".txt";
string fileloc = path + projname;
// FileStream fs = null;
if (!File.Exists(fileloc))
{
using (TextWriter txt = new StreamWriter(fileloc))
{
// TextWriter txt = new StreamWriter(fileloc);
txt.Write(noteFrm.NoteText + Environment.NewLine);
txt.Close();
}
}
else if (File.Exists(fileloc))
{
using (var txt = new StreamWriter(fileloc, true))
{
txt.BaseStream.Seek(0, SeekOrigin.End);
txt.Write(noteFrm.NoteText + Environment.NewLine);
txt.Close();
}
}
//noteFrm.NoteText="";
//get Note Text
_timeCard.NoteText = noteFrm.NoteText;
Utils.LogManager.write("New Note Text: " + noteFrm.NoteText);
}
}

If you want the file to always match what is in the text box, then I'd suggest that you replace your whole if (!File.Exists(fileloc)) block with just this:
File.WriteAllText(fileloc, noteFrm.NoteText + Environment.NewLine);
That will create the file if needed, open the file, replace all the contents with what is in the text box, and close the file.

Related

How to decide and display to the user when a file/folder have been copied or file/folder have been created when using filesystemwatcher?

private void Fsw_Created(object sender, FileSystemEventArgs e)
{
if (!e.FullPath.Contains("$RECYCLE.BIN"))
{
string time = DateTime.Now.ToString("h:mm:ss tt");
if (DateTime.Now.Subtract(_lastTimeFileWatcherEventRaised).TotalMilliseconds < 100)
{
return;
}
_lastTimeFileWatcherEventRaised = DateTime.Now;
Dispatcher.Invoke(() =>
{
if (!StringFromRichTextBox(RichTextBoxLogger).Contains(e.FullPath))
{
FileInfo info = new FileInfo(e.FullPath);
TextRange rangeOfText1 = new TextRange(RichTextBoxLogger.Document.ContentEnd, RichTextBoxLogger.Document.ContentEnd);
rangeOfText1.Text = "\r" + e.Name + " Created At : " + time;
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightCyan);
rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
// The copy part is not working good yet.
// when creating a new file it's saying the file have been copied.
// it should say file created only when creating a new file and not copied.
// it should say file copied now only when copying from other directory/ies.
/*if (File.Exists(e.FullPath))
{
foreach (var key in dic.Keys)
{
if (key.Contains(System.IO.Path.GetFileName(e.FullPath)))
{
TextRange rangeOfText2 = new TextRange(RichTextBoxLogger.Document.ContentEnd, RichTextBoxLogger.Document.ContentEnd);
rangeOfText2.Text = "\r" + "The File " + System.IO.Path.GetFileName(e.FullPath) +
" Copied From " + System.IO.Path.GetDirectoryName(key)
+ " To " + System.IO.Path.GetDirectoryName(e.FullPath);
rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightCyan);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
break;
}
}
}*/
}
});
}
}
I can make either copied or created because if i'm using the copy part it will display a file copied when i'm creating a new file. and the other way if copy a file and using the created part.
i'm also not sure i'm using fine in the copy part to get the original source folder of the copied file to show the user where the file is copied from.
the variable dic in the copy part is a dictionary<string, long> type. and i'm using it first time like that :
private void Bgw_DoWork(object sender, DoWorkEventArgs e)
{
fileslist = GetFiles(getFilesString, "*.*", fswIncludeDirectoriesFlag).ToList();
if (bgw.CancellationPending == true)
{
e.Cancel = true;
return;
}
if (fileslist.Count > 0)
{
bgw.ReportProgress(fileslist.Count);
for (int i = 0; i < fileslist.Count; i++)
{
if (bgw.CancellationPending == true)
{
e.Cancel = true;
return;
}
FileInfo info = new FileInfo(fileslist[i]);
if (File.Exists(info.FullName))
{
dic.Add(fileslist[i], info.Length);
}
}
}
}
what i'm trying to archive is when the user create a new file display something like :
"The file: Test.txt have been created in d:"
and if the user copy a file then display something like :
"The file: Test.txt have been copied from the folder D:\ to the folder D:\Testing12345"
Updating on my progress :
Ok, this is working fine for both cases. when i'm copying a file to another folder it will display that the file created in the other folder and also copied to the other folder.
if (!StringFromRichTextBox(RichTextBoxLogger).Contains(e.FullPath))
{
FileInfo info = new FileInfo(e.FullPath);
TextRange rangeOfText1 = new TextRange(RichTextBoxLogger.Document.ContentEnd, RichTextBoxLogger.Document.ContentEnd);
rangeOfText1.Text = "\r" + e.Name + " Created At : " + time;
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightCyan);
rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
foreach (var key in dic.Keys)
{
if (key.Contains(System.IO.Path.GetFileName(e.FullPath)))
{
TextRange rangeOfText2 = new TextRange(RichTextBoxLogger.Document.ContentEnd, RichTextBoxLogger.Document.ContentEnd);
rangeOfText2.Text = "\r" + "The File " + System.IO.Path.GetFileName(e.FullPath) +
" Copied From " + System.IO.Path.GetDirectoryName(key)
+ " To " + System.IO.Path.GetDirectoryName(e.FullPath);
rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightCyan);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
break;
}
}
}
it's logic because the file copied to another folder and also the file created is now exist in the other folder.
I think the simplest way to detect if file have been copied or created is to check if the file have a destination folder. for example if i copied a file from D:\ to D:\Test\ then the file source folder is D:\ and the destination folder is D:\Test\ so that's mean the file have been copied.
if i created a file in D:\Test\ so the file source folder is D:\Test\ that's mean there is no destination folder only source folder.
with that logic i think i will be able to check if file have been copied or only created.
I will try it.

How to copy data from HTML div in Selenium C#?

I want to copy alter table data from webpage div and paste it into a .txtfile, screenshot is attached below:
Below is the HTML for above screenshot:
Can i do this by storing this in a variable like below but how can i copy all data at once in a variable from div ?
string value = driver.FindElement(By.XPath("//td[#style='padding:0px;
white-space: nowrap;']")).Text;
Below is the code of my test case in which i am selecting a file to convert from a tool after conversion i want to store the alter table script in a separate .txt file for which i created a create function to create file :
public void TestMethod1()
{
try
{
string dir = #"D:\test\input"; //path
var directory = new DirectoryInfo(dir); //folder ko access
foreach (FileInfo file in directory.GetFiles()) //loop
IWebDriver driver = new ChromeDriver(); //driver object
driver.Navigate().GoToUrl("http:abcurl//convPLSQL.html");
//site url
driver.Manage().Window.Maximize(); //browser maximize
string param = dir.Replace("/", "\\"); // ye code file
param += "\\";
param += file.Name;
driver.FindElement(By.Id("fileuploader")).SendKeys(param);
driver.FindElement(By.Id("keyinput")).SendKeys("convUser001");//Key
driver.FindElement(By.Id("translatebutton")).Click();//Translate Button
driver.FindElement(By.LinkText("Download Results")).Click();//Download
// string data= driver.FindElement(By.XPath("//td[#style='padding:0px;
// white-space:nowrap;']")).Text;
create(); // call create function to create .txt file
}
public void create()
{
try
{
string fileName = #"D:\test\output\Mahesh.txt";
// Check if file already exists. If yes, delete it.
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
// Create a new file
using (FileStream fs = System.IO.File.Create(fileName))
{
// Add some text to file
Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");
fs.Write(title, 0, title.Length);
byte[] author = new UTF8Encoding(true).GetBytes("Mahesh Chand");
fs.Write(author, 0, author.Length);
}
// Open the stream and read it back.
using (StreamReader sr = System.IO.File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
System.Console.WriteLine(s);
}
}
Get all child elements of div containing the spans having the needed text. Something like:
var spans = driver.FindElements(By.XPath("//td/div[2]/span"));
Then concatenate text from each span element. Replace special characters like "&nbsp" with space. Use string builder or add text to string generic collection and join later if the text is big.
Example:
var text = string.Empty;
foreach(var span in spans)
{
text += span.Text.Replace("&nbsp", " ");
}

Characters being copied are getting multiplied on the text file on c# windows form

I am creating a simple clipboard system on C# and every time characters or words are copied, they are getting multiplied on the text file just like on the picture below.
here is my code
string path = #"C:\\Users\\" + Environment.UserName + "\\Documents\\clipboard.txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path)) ;
if(File.Exists(path))
{
while (true)
{
var text = Clipboard.GetText();
File.AppendAllText(path, text);
Thread.Sleep(2500);
}
}
}
This is a pretty crude fix and I'm sure that there's a much more efficient way to do it than this, but for the time being this should work.
You'll store the last copied text as lastText and compare it to the current text in text, if they match up then your clipboard hasn't changed, if they don't then you've got new text on your clipboard and should append it to the file.
string path = #"C:\\Users\\" + Environment.UserName + "\\Documents\\clipboard.txt";
string lastText = "";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path)) ;
if(File.Exists(path))
{
while (true)
{
var text = Clipboard.GetText();
if(lastText != text)
{
File.AppendAllText(path, text);
lastText = text;
}
Thread.Sleep(2500);
}
}
}

how to save data that has been edited in the console to a file

I have an original file that needs editing, I have managed to open this file and used code to correct the problems I have been asked to this has been done by changed the original file into a string, Now I need to save these changes, how do I save to a new file what is being displayed on the console? I have tried using stream writer but don't know how to save the edited string.
New answer based on new/detailed requirements:
I modified your code and added some new lines.
string path = #"c:\temp\MyIOFile.txt";
try
{
string file = File.ReadAllText(path);
//The code wrote to the right hand side finds the file listed from my C drive
string longstr = file;
string[] strs = longstr.Split(':', '*');
foreach (string ss in strs)
{
Console.WriteLine(ss);
}
//before text is written, you say you want to modify it
string newText = "*enter new file contents here*";
//you can add new text (Append) or
//change all the contents of the file
//set the value of whatToDo to "Append" to add new text to the file
//set the value of whatToDo to any value other than "Append" to replace
//the entire contents of the filw with the data in variable newText
string whatToDo = "Append";
if (whatToDo == "Append")
{
//append to existing text
//variable file contains old text
//varaible newText contains the new text to be appended
File.AppendAllText(path, newText);
}
else
{
//creates new contents in the file.
//varaiable new text contains the new text representing
//file contents
File.WriteAllText(path, newText);
}
//string file = File.AppendAllText(#"C:\Users\path\.......");
}
catch (Exception ex)
{
Console.WriteLine("*** Error:" + ex.Message);
}
Console.WriteLine("*** Press Enter key to exit");
Console.ReadLine();
}
Original Answer
May be this could help:
string path = #"c:\temp\MyIOFile.txt";
if (!File.Exists(path))
{
// File does not exist - What do you want to do?
}
try
{
// Open the file to read from and store result in a string variable
string readText = File.ReadAllText(path);
// modify the text somehow before appending to file
string appendText =readText+ Environment.NewLine+ "This is extra text";
File.AppendAllText(path, appendText, Encoding.UTF8);
}
catch (Exception ex)
{
Console.WriteLine ("***Error:" + ex.Message);
// display errors
}
string file = File.ReadAllText(#"C:\Users\path.......");
//The code wrote to the right hand side finds the file listed from my C drive
string longstr = file;
string[] strs = longstr.Split(':', '*');
foreach (string ss in strs)
{
Console.WriteLine(ss);
}
string file = File.AppendAllText(#"C:\Users\path\.......");
Console.ReadLine();

Expression encoder: change file name after encoding

I'm using Microsoft Expression Encoder and this is my code
using (LiveJob job = new LiveJob())
{
// Creates file source for encoding
LiveFileSource fileSource = job.AddFileSource(DataDirectory);
// Sets playback to loop on reaching the end of the file
fileSource.PlaybackMode = FileSourcePlaybackMode.Jump;
// Sets this source as the current active one
job.ActivateSource(fileSource);
job.ApplyPreset(LivePresets.VC1IISSmoothStreamingLowBandwidthStandard);
PushBroadcastPublishFormat format = new PushBroadcastPublishFormat();
format.PublishingPoint = new Uri(PublishPoint);
job.PublishFormats.Add(format);
// Starts encoding
job.StartEncoding();
}
this code encode a list of files in a directory when he finish one he jump to the next
what I want to do is change the file name when it's encoded before passing to th other one
I have added this Methode I don't know if it work or no
public void liveJob_Status(object sender, EncodeStatusEventArgs e)
{
if (e.Status == EncodeStatus.Jumped)
{ LiveFileSource file = (LiveFileSource)e.LiveSource;
string name = file.Name;
string modified_name = "Encode" + name;
File.Move(DataDirectory + #"\" + name, DataDirectory + #"\" + name.Replace(name, modified_name));
}
}

Categories