Add a string property to a linklabel? - c#-4.0

I am currently making an "app launcher" which reads a text file line by line. Each line is a path to a useful program somewhere else on my pc. A link label is automatically made for each path (i.e. each line) in the text file.
I would like the .Text property of the link label to be an abbreviated form of the path (i.e. just the file name, not the whole path). I have found out how to shorten the string in this way (so far so good !)
However, I would also like to store the full path somewhere - as this is what my linklabel will need to link to. In Javascript I could pretty much just add this property to linklabel like so: mylinklabel.fullpath=line; (where line is the current line as we read through the text file, and fullpath is my "custom" property that I would like to try and add to the link label. I guess it needs declaring, but I am not sure how.
Below is the part of my code which creates the form, reads the text file line by line and creates a link label for the path found on each line:
private void Form1_Load(object sender, EventArgs e) //on form load
{
//System.Console.WriteLine("hello!");
int counter = 0;
string line;
string filenameNoExtension;
string myfile = #"c:\\users\matt\desktop\file.txt";
//string filenameNoExtension = Path.GetFileNameWithoutExtension(myfile);
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
//MessageBox.Show(line); //check whats on each line
LinkLabel mylinklabel = new LinkLabel();
filenameNoExtension = Path.GetFileNameWithoutExtension(line); //shortens the path to just the file name without extension
mylinklabel.Text = filenameNoExtension;
//string fullpath=line; //doesn't work
//mylinklabel.fullpath=line; //doesn't work
mylinklabel.Text = filenameNoExtension; //displays the shortened path
this.Controls.Add(mylinklabel);
mylinklabel.Location = new Point(0, 30 + counter * 30);
mylinklabel.AutoSize = true;
mylinklabel.VisitedLinkColor = System.Drawing.Color.White;
mylinklabel.LinkColor = System.Drawing.Color.White;
mylinklabel.Click += new System.EventHandler(LinkClick);
counter++;
}
file.Close();
}
So, how can I store a full path as a string inside the linklabel for use in my onclick function later on?

You could derive a new custom class or you could use a secondary data store for your additional info the easiest solution would be to use a dictionary.
dictonary<string,string> FilePaths = new dictonary<string,string>();
private void Form1_Load(object sender, EventArgs e) //on form load
{
...
FilePath[filenameNoExtension] = line;
}
You Can Access the Path
FilePath[mylinklabel.Tex]

One option you have is to have a method that truncates your string (and even adds "..."). You can then store the full path in the Tag property of the Linklabel. And here's an example of the first part (truncating the text).
public static string Truncate(this string s, int maxLength)
{
if (string.IsNullOrEmpty(s) || maxLength <= 0)
return string.Empty;
else if (s.Length > maxLength)
return s.Substring(0, maxLength) + "...";
else
return s;
}
Hope that helps some

Related

How to avoid extra line feeds in MIME export?

I'm exporting MIME eMails with the following code:
public String fromRawMime(final Session s, final Document doc) throws NotesException {
final Stream notesStream = s.createStream();
final MIMEEntity rootMime = doc.getMIMEEntity();
// check if it is multi-part or single
if (rootMime.getContentType().equals("multipart")) {
this.printMIME(rootMime, notesStream);
} else {
// We can just write the content into the
// Notes stream to get the bytes
rootMime.getEntityAsText(notesStream);
}
// Write it out
notesStream.setPosition(0);
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.append(notesStream.read());
notesStream.close();
notesStream.recycle();
rootMime.recycle();
return out.toString();
}
// Write out a mime entry to a Stream object, includes sub entries
private void printMIME(final MIMEEntity mimeRoot, final Stream out) throws NotesException {
if (mimeRoot == null) {
return;
}
// Encode binary as base64
if (mimeRoot.getEncoding() == MIMEEntity.ENC_IDENTITY_BINARY) {
mimeRoot.decodeContent();
mimeRoot.encodeContent(MIMEEntity.ENC_BASE64);
}
out.writeText(mimeRoot.getBoundaryStart(), Stream.EOL_NONE);
mimeRoot.getEntityAsText(out);
out.writeText(mimeRoot.getBoundaryEnd(), Stream.EOL_NONE);
if (mimeRoot.getContentType().equalsIgnoreCase("multipart")) {
// Print preamble if it isn't empty
final String preamble = mimeRoot.getPreamble();
if (!preamble.isEmpty()) {
out.writeText(preamble, Stream.EOL_NONE);
}
// Print content of each child entity - recursive calls
// Include recycle of mime elements
MIMEEntity mimeChild = mimeRoot.getFirstChildEntity();
while (mimeChild != null) {
this.printMIME(mimeChild, out);
final MIMEEntity mimeNext = mimeChild.getNextSibling();
// Recycle to ensure we don't bleed memory
mimeChild.recyle();
mimeChild = mimeNext;
}
}
}
The result contains one empty line for each line. Including the content that gets added using getEntityAsText. What am I missing to get rid of the extra lines?
The email RFCs require the use of CRLF to terminate text lines.
You are using EOL_NONE, so the writeText method isn't adding anything to the text, but apparently both the CR and LF are being treated as newlines in your output. You may want to try using out.writeText with EOL_PLATFORM instead.
The devils is in the details...
the printMIME function works just fine. Changing the EOL didn't have an impact. However I added EOL_PLATFORM later on for the final result to separate the headers from the content.
The offending code is this:
notesStream.setPosition(0);
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.append(notesStream.read());
notesStream.close();
Turns out that it seems to interpret whatever was in the MIME as 2 line feeds. So the code needs to be changed to:
notesStream.setPosition(0);
String out = notesStream.readText();
notesStream.close();
so instead of a OutputStream I needed a String and instead of read() I needed readText(). Now working happily in my "project castle"

BufferedReader is sometimes empty

I have Loader class where I load txt file into BufferedReader from resources and return this field. I use this method but it acts really strange(for me). When I don't put
String str = bufferReader.readLine(); after
bufferReader = new BufferedReader(fileReader);
(in Loader class) than bufferReader in another class is empty, and readLine() returns null. When I write that piece of code in Loader class, I can read each line from txt, except the 1. one which is read in Loader class. Also, I can't read last line if I dont put enter at the end.
public BufferedReader loadFromFileToBufferReader(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
System.out.print(getClass().getClassLoader().getResource("resources/" + fileName));
File file = new File(classLoader.getResource("resources/" + fileName).getFile());
BufferedReader bufferReader = null;
try (FileReader fileReader = new FileReader(file)) {
bufferReader = new BufferedReader(fileReader);
String str = bufferReader.readLine();
} catch (IOException e) {
System.err.println("Something went terribly wrong with file reading");
}
return bufferReader;
}
and usage:
public Database() {
productsInDatabse = new ArrayList<>();
codesList = new ArrayList<>();
loader = new LoadFromFile();
BufferedReader output = loader.loadFromFileToBufferReader("database.txt");
Product product;
String line;
String[] array;
try {
line = output.readLine();
while (line != null) {
You should paste your code here because it's hard to deduce all the possible causes of this without seeing the code on 100% but I am guessing you have it the same file open at the same time from multiple sources without closing it before from one? Could be literally millions of little things, just telling you how the same error happened to me.

Getting Values out of a String with patterns

I have textfiles, which have attributes saved in Strings. Those Strings have a pattern like this:
[attributeName]:[value]
I can't generalize the [value], because it could be of any primitive datatype.
Saving the effectively values is not my concern, because it's depending on the user which attribute has to be loaded. The same file won't be loaded very often.
Now I have 2 problems:
1) For some reason the program which creates those files sometimes adds spaces around the : at some attributes and [value] could also contain spaces, so I have to get rid of those
2) Making the reading of those attributes more performant:
I've come up with this method:
public String getAttribute(File file, String attribute)
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(file), 1024);
String line;
Pattern p = Pattern.compile(Pattern.quote(attribute), Pattern.CASE_INSENSITIVE);
while ((line = reader.readLine()) != null)
{
int i = line.indexOf(":");
if(line.charAt(i-1) == ' ')
line = line.substring(0,i-2) + line.substring(i);
if(line.charAt(i+1) == ' ')
line = line.substring(0,i) + line.substring(i+2);
if (p.matcher(line).find())
{
return line.replace(attribute, "").trim();
}
}
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
However, this method will probably be one of the most called by my application, so I can't leave it so unperformant as it is right now,
Thanks for any help!
I modified code to find appropriate line. Check example code below.
If you have a lot of files and attributes in these files you could think about saving somewhere pair attribute=value in code. In example code I provided very primitive cache by using Table interface from guava library.
Example code:
# guava library
import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;
# apache commons lang
import static org.apache.commons.lang.StringUtils.startsWithIgnoreCase;
# apache commons io
import static org.apache.commons.io.IOUtils.closeQuietly;
[...]
# very primitive cache implementation. To find a value in table you have to
# pass row and column keys. In this implementation row is equal to file
# absolute path (because you can have 2 files with the same name) and column
# is equal to attribute name.
# If you have a lot of files and attributes probably you will have to clear
# from time to time the cache otherwise you will get out of memory
private static final Table<String, String, String> CACHE = HashBasedTable.create();
[...]
public String getAttribute(File file, String attribute) {
# get value for the given attribute from the given file
String value = CACHE.get(file.getAbsolutePath(), attribute);
# if cache does not contain value, method will read value from file
if (null == value) {
BufferedReader reader = null;
String value = null;
try {
reader = new BufferedReader(new FileReader(file), 1024);
String line;
while ((line = reader.readLine()) != null) {
# From your description I understood that each line in file
# starts with attribute name
if (startsWithIgnoreCase(line, attribute) {
# if we found correct line we simple split it by ':'
String[] array = line.split(":");
# this is to ensure that line contains attribute name
# and value
if (array.length >= 2) {
# we found value for attribute and we remove spaces
value = array[1].trim();
# we put value to the cache to speed up finding
# value for the same attribute in the future
CACHE.put(file.getAbsolutePath(), attribute, value);
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
# you should always close
closeQuietly(reader);
}
}
return value;
}

Automate Resharper's "to property with backing field" across many properties and classes?

I've got some C# code like this (class file = Status.cs):
/// <summary>
/// Constructs a status entity with the text specified
/// </summary>
/// <param name="someParameter">Some parameter.</param>
public Status(string someParameter)
{
SomeProperty = someParameter;
}
/// <summary>
/// An example of a virtual property.
/// </summary>
public virtual string SomeProperty { get; private set; }
And I want to do 3 things to it:
perform a Resharper "to property with backing field" on it
get rid of the "private set" and replace it with a regular "set"
change the constructor so it initializes the private field instead of the property
So the end result would look like this:
/// <summary>
/// Constructs a status entity with the text specified
/// </summary>
/// <param name="someParameter">Some parameter.</param>
public Status(string someParameter)
{
_someProperty = someParameter;
}
private string _someProperty;
/// <summary>
/// An example of a virtual property.
/// </summary>
public virtual string SomeProperty
{
get { return _someProperty; }
set { _someProperty = value; }
}
And my question is: Is there a way to automate this type of refactoring using, say, the Resharper API ?
Background:
For those who might wonder why I want to do this, it's because:
I'm upgrading NHibernate (old=2.1.2.4000, new=3.3.1.4000) and Fluent NHibernate (old=1.1.0.685, new=1.3.0.0).
I've got rid of the old NHibernate.ByteCode.Castle.dll and the corresponding line in the config file, so I can now use the default proxy that's built into the latest NHibernate.
Between the new implementation of NHibernate and the new version of Fluent, there seem to be two problems when I try to build and run unit tests (part of this is FxCop complaining, but anyway):
a) exceptions are thrown because of the "private set", and
b) exceptions are thrown because the virtual property is being initialized in the constructor.
So I found that if I make those changes, it compiles and the unit tests pass.
So that's fine for a class or two, but there are over 800 class files and who knows how many properties.
I'm sure there are lots of ways to do this (e.g. using reflection, recursing through the directories and parsing the files etc), but it seems like Resharper is the proper tool for something like this.
Any help appreciated, thank you, -Dave
--In response to the answer saying "just change it to a protected set and you're done":
Unfortunately it’s not that simple.
Here is the error that occurs on running unit tests (before making any changes to any class):
Test method threw exception:
NHibernate.InvalidProxyTypeException: The following types may not be used as proxies:
.Status: method set_StatusText should be 'public/protected virtual' or 'protected internal virtual'
..Status: method set_Location should be 'public/protected virtual' or 'protected internal virtual'
So if I change the class as suggested (where the only change is to change the “private set” to a “protected set”), the project will not build, because:
Error 2 CA2214 : Microsoft.Usage : 'Status.Status(string, StatusLocation)' contains a call chain that results in a call to a virtual method defined by the class. Review the following call stack for unintended consequences:
Status..ctor(String, StatusLocation)
Status.set_Location(StatusLocation):Void C:\\Status.cs 28
That is why it is also necessary to change any statement in the constructor which initializes one of these virtual properties.
The previous implementation of the NHibernate proxy (ByteCode.Castle) did not seem to care about the “private set”, whereas this one does.
And, admittedly, the second error is because of FxCop, and I could just put an attribute on the class to tell FxCop not to complain about this, but that seems to just be making the problem go away, and initializing virtual properties in constructors is, as I understand it, bad practice anyway.
So my question still stands. The changes I initially described are the changes I would like to make. How can I automate these changes?
I went ahead and wrote a C# utility to parse such a class file. The "protected set" idea is valid to a point (thanks Hazzik), but it still needs a backing field. The below code produces the output I described above (except uses a "protected set"). Regards, -Dave
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
// TODO: write recursive algorithm to loop through directories
// TODO: handle generic collections as Fluent NHibernate treats those differently
class Program
{
public static string ConvertInitialCapitalToUnderscoreAndLowerCase(string input)
{
var firstChar = input.Substring(0, 1);
var restOfStmt = input.Substring(1);
var newFirst = "_" + firstChar.ToLower();
var output = newFirst + restOfStmt;
return output;
}
// this gets any tabs or spaces at the beginning of the line of code as a string,
// so as to preserve the indentation (and/or add deeper levels of indentation)
public static string GetCodeLineIndentation(string input)
{
var charArray = input.ToCharArray();
var sbPrefix = new StringBuilder();
foreach (var c in charArray)
{
// if it's a tab or a space, add it to the "prefix"
if (c == 9 || c == ' ')
{
sbPrefix.Append(c);
}
else
{
// get out as soon as we hit the first ascii character (those with a value up to 127)
break;
}
}
return sbPrefix.ToString();
}
static void Main(string[] args)
{
const string path = #"C:\pathToFile\Status.cs";
Console.WriteLine("Examining file: " + path);
if (!File.Exists(path))
{
Console.WriteLine("File does not exist: " + path);
throw new FileNotFoundException(path);
}
// Read the file.
var arrayOfLines = File.ReadAllLines(path);
// Convert to List<string>
var inputFileAsListOfStrings = new List<string>(arrayOfLines);
// See if there are any virtual properties.
var virtualProps = inputFileAsListOfStrings.Where(s => s.Contains("public virtual")).ToList();
// See if there are any "private set" strings.
var privateSets = inputFileAsListOfStrings.Where(s => s.Contains("private set")).ToList();
if (virtualProps.Count > 0)
{
Console.WriteLine("Found " + virtualProps.Count + " virtual properties in the class...");
}
if (privateSets.Count > 0)
{
Console.WriteLine("Found " + privateSets.Count + " private set statements in the class...");
}
// Get a list of names of the virtual properties
// (the 4th "word", i.e. index = 3, in the string, will be the property name,
// e.g. "public virtual string SomePropertyName"
var virtualPropNames = virtualProps.Select(vp => vp.Trim().Split(' ')).Select(words => words[3]).ToList();
if (virtualPropNames.Count() != virtualProps.Count())
{
throw new Exception("Error: the list of virtual property names does not equal the number of virtual property statements!");
}
// Find all instances of the virtual properties being initialized.
// By examining the overall file for instances of the virtual property name followed by an equal sign,
// we can identify those lines which are statements initializing the virtual property.
var initializeStatements = (from vpName in virtualPropNames
from stmt in inputFileAsListOfStrings
let stmtNoSpaces = stmt.Trim().Replace(" ", "")
where stmtNoSpaces.StartsWith(vpName + "=")
select stmt).ToList();
if (initializeStatements.Count() > 0)
{
Console.WriteLine("Found " + initializeStatements.Count + " initialize statements in the class...");
}
// now process the input based on the found strings and write the output
var outputFileAsListOfStrings = new List<string>();
foreach (var inputLineBeingProcessed in inputFileAsListOfStrings)
{
// is the input line one of the initialize statements identified previously?
// if so, rewrite the line.
// e.g.
// old line: StatusText = statusText;
// becomes: _statusText = statusText;
var isInitStmt = false;
foreach (var initStmt in initializeStatements)
{
if (inputLineBeingProcessed != initStmt) continue;
// we've found our statement; it is an initialize statement;
// now rewrite the format of the line as desired
var prefix = GetCodeLineIndentation(inputLineBeingProcessed);
var tabAndSpaceArray = new[] {' ', '\t'};
var inputLineWithoutPrefix = inputLineBeingProcessed.TrimStart(tabAndSpaceArray);
var outputLine = prefix + ConvertInitialCapitalToUnderscoreAndLowerCase(inputLineWithoutPrefix);
// write the line (preceded by its prefix) to the output file
outputFileAsListOfStrings.Add(outputLine);
Console.WriteLine("Rewrote INPUT: " + initStmt + " to OUTPUT: " + outputLine);
isInitStmt = true;
// we have now processed the input line; no need to loop through the initialize statements any further
break;
}
// if we've already determined the current input line is an initialize statement, no need to proceed further;
// go on to the next input line
if (isInitStmt)
continue;
// is the input line one of the "public virtual SomeType SomePropertyName" statements identified previously?
// if so, rewrite the single line as multiple lines of output.
// the input will look like this:
/*
public virtual SomeType SomePropertyName { get; set; }
*/
// first, we'll need a private variable which corresponds to the original statement in terms of name and type.
// what we'll do is, write the private field AFTER the public property, so as not to interfere with the XML
// comments above the "public virtual" statement.
// the output will be SIX LINES, as follows:
/*
public virtual SomeType SomePropertyName
{
get { return _somePropertyName; }
protected set { _someProperty = value; }
}
private SomeType _somePropertyName;
*/
var isPublicVirtualStatement = false;
foreach (var vp in virtualProps)
{
if (inputLineBeingProcessed != vp) continue;
// the input line being processed is a "public virtual" statement;
// convert it into the six line output format
var thisOutputList = new List<string>();
// first separate any indentation "prefix" that may exist (i.e. tabs and/or spaces),
// from the actual string of text representing the line of code
var prefix = GetCodeLineIndentation(inputLineBeingProcessed);
var tabAndSpaceArray = new[] { ' ', '\t' };
var inputLineWithoutPrefix = inputLineBeingProcessed.TrimStart(tabAndSpaceArray);
var originalVpStmt = inputLineWithoutPrefix.Split(' ');
// first output line (preceded by its original prefix)
var firstOutputLine = prefix +
originalVpStmt[0] + ' ' +
originalVpStmt[1] + ' ' +
originalVpStmt[2] + ' ' +
originalVpStmt[3];
thisOutputList.Add(firstOutputLine);
// second output line (indented to the same level as the original prefix)
thisOutputList.Add(prefix + "{");
// get field name from property name
var fieldName = ConvertInitialCapitalToUnderscoreAndLowerCase(originalVpStmt[3]);
// third output line (indented with the prefix, plus one more tab)
var thirdOutputLine = prefix + "\t" + "get { return " + fieldName + "; }";
thisOutputList.Add(thirdOutputLine);
// fourth output line (indented with the prefix, plus one more tab)
var fourthOutputLine = prefix + "\t" + "protected set { " + fieldName + " = value; }";
thisOutputList.Add(fourthOutputLine);
// fifth output line (indented to the same level as the first curly bracket)
thisOutputList.Add(prefix + "}");
// sixth output line (the "index 2" value of the original statement will be the string representing the .Net type)
// (indentation is the same as the "public virtual" statement above)
var sixthOutputLine = prefix +
"private" + ' ' +
originalVpStmt[2] + ' ' +
fieldName + ";";
thisOutputList.Add(sixthOutputLine);
// now write the six new lines to the master output list
outputFileAsListOfStrings.AddRange(thisOutputList);
isPublicVirtualStatement = true;
Console.WriteLine("Rewrote INPUT: " + inputLineBeingProcessed + " to OUTPUT: <multi-line block>");
break;
}
// if we've already determined the current input line is a "public virtual" statement, no need to proceed further;
// go on to the next input line
if (isPublicVirtualStatement)
continue;
// if we've gotten this far, the input statement is neither an "initialize" statement, nor a "public virtual" statement;
// So just write the output. Don't bother logging this as most lines will not be ones we'll process.
outputFileAsListOfStrings.Add(inputLineBeingProcessed);
}
// write the output file
var newPath = path.Replace(".cs", "-NEW.cs");
File.WriteAllLines(newPath, outputFileAsListOfStrings);
}
}

Console application: How to update the display without flicker?

Using C# 4 in a Windows console application that continually reports progress how can I make the "redraw" of the screen more fluid?
I'd like to do one of the following:
- Have it only "redraw" the part of the screen that's changing (the progress portion) and leave the rest as is.
- "Redraw" the whole screen but not have it flicker.
Currently I re-write all the text (application name, etc.). Like this:
Console.Clear();
WriteTitle();
Console.WriteLine();
Console.WriteLine("Deleting:\t{0} of {1} ({2})".FormatString(count.ToString("N0"), total.ToString("N0"), (count / (decimal)total).ToString("P2")));
Which causes a lot of flickering.
Try Console.SetCursorPosition. More details here: How can I update the current line in a C# Windows Console App?
static void Main(string[] args)
{
Console.SetCursorPosition(0, 0);
Console.Write("################################");
for (int row = 1; row < 10; row++)
{
Console.SetCursorPosition(0, row);
Console.Write("# #");
}
Console.SetCursorPosition(0, 10);
Console.Write("################################");
int data = 1;
System.Diagnostics.Stopwatch clock = new System.Diagnostics.Stopwatch();
clock.Start();
while (true)
{
data++;
Console.SetCursorPosition(1, 2);
Console.Write("Current Value: " + data.ToString());
Console.SetCursorPosition(1, 3);
Console.Write("Running Time: " + clock.Elapsed.TotalSeconds.ToString());
Thread.Sleep(1000);
}
Console.ReadKey();
}
I know this question is a bit old but I found if you set Console.CursorVisible = false then the flickering stops as well.
Here's a simple working demo that shows multi-line usage without flickering. It shows the current time and a random string every second.
private static void StatusUpdate()
{
var whiteSpace = new StringBuilder();
whiteSpace.Append(' ', 10);
var random = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var randomWord = new string(Enumerable.Repeat(chars, random.Next(10)).Select(s => s[random.Next(s.Length)]).ToArray());
while (true)
{
Console.SetCursorPosition(0, 0);
var sb = new StringBuilder();
sb.AppendLine($"Program Status:{whiteSpace}");
sb.AppendLine("-------------------------------");
sb.AppendLine($"Last Updated: {DateTime.Now}{whiteSpace}");
sb.AppendLine($"Random Word: {randomWord}{whiteSpace}");
sb.AppendLine("-------------------------------");
Console.Write(sb);
Thread.Sleep(1000);
}
}
The above example assumes your console window is blank to start. If not, make sure to use Console.Clear() first.
Technical Note:
SetCursorPosition(0,0) places the cursor back to the top (0,0) so the next call to Console.Write will start from line 0, char 0. Note, it doesn't delete the previous content before writing. As an example, if you write "asdf" over a previous line such as "0123456", you'll end up with something like "asdf456" on that line. For that reason, we use a whiteSpace variable to ensure any lingering characters from the previous line are overwritten with blank spaces. Adjust the length of the whiteSpace variable to meet your needs. You only need the whiteSpace variable for lines that change.
Personal Note:
For my purposes, I wanted to show the applications current status (once a second) along with a bunch of other status information and I wanted to avoid any annoying flickering that can happen when you use Console.Clear(). In my application, I run my status updates behind a separate thread so it constantly provides updates even though I have numerous other threads and long running tasks going at the same time.
Credits:
Thanks to previous posters and dtb for the random string generator used in the demo.
How can I generate random alphanumeric strings in C#?
You could try to hack something together using the core libraries.
Rather than waste your time for sub-standard results, I would check out this C# port of the ncurses library (which is a library used for formatting console output):
Curses Sharp
I think you can use \r in Windows console to return the beginning of a line.
You could also use SetCursorPosition.
I would recommend the following extension methods. They allow you to use a StringBuilder to refresh the console view without any flicker, and also tidies up any residual characters on each line
The Problem: The following demo demonstrates using a standard StringBuilder, where updating lines that are shorter than the previously written line get jumbled up. It does this by writing a short string, then a long string on a loop:
public static void Main(string[] args)
{
var switchTextLength = false;
while(true)
{
var sb = new StringBuilder();
if (switchTextLength)
sb.AppendLine("Short msg");
else
sb.AppendLine("Longer message");
sb.UpdateConsole();
switchTextLength = !switchTextLength;
Thread.Sleep(500);
}
}
Result:
The Solution: By using the extension method provided below, the issue is resolved
public static void Main(string[] args)
{
var switchTextLength = false;
while(true)
{
var sb = new StringBuilder();
if (switchTextLength)
sb.AppendLineEx("Short msg");
else
sb.AppendLineEx("Longer message");
sb.UpdateConsole();
switchTextLength = !switchTextLength;
Thread.Sleep(500);
}
}
Result:
Extension Methods:
public static class StringBuilderExtensions
{
/// <summary>
/// Allows StrinbBuilder callers to append a line and blank out the remaining characters for the length of the console buffer width
/// </summary>
public static void AppendLineEx(this StringBuilder c, string msg)
{
// Append the actual line
c.Append(msg);
// Add blanking chars for the rest of the buffer
c.Append(' ', Console.BufferWidth - msg.Length - 1);
// Finish the line
c.Append(Environment.NewLine);
}
/// <summary>
/// Combines two StringBuilders using AppendLineEx
/// </summary>
public static void AppendEx(this StringBuilder c, StringBuilder toAdd)
{
foreach (var line in toAdd.ReadLines())
{
c.AppendLineEx(line);
}
}
/// <summary>
/// Hides the console cursor, resets its position and writes out the string builder
/// </summary>
public static void UpdateConsole(this StringBuilder c)
{
// Ensure the cursor is hidden
if (Console.CursorVisible) Console.CursorVisible = false;
// Reset the cursor position to the top of the console and write out the string builder
Console.SetCursorPosition(0, 0);
Console.WriteLine(c);
}
}
I actually had this issue so I made a quick simple method to try and eliminate this.
static void Clear(string text, int x, int y)
{
char[] textChars = text.ToCharArray();
string newText = "";
//Converts the string you just wrote into a blank string
foreach(char c in textChars)
{
text = text.Replace(c, ' ');
}
newText = text;
//Sets the cursor position
Console.SetCursorPosition(x, y);
//Writes the blank string over the old string
Console.WriteLine(newText);
//Resets cursor position
Console.SetCursorPosition(0, 0);
}
It actually worked surprisingly well and I hope it may work for you!
Naive approach but for simple applications is working:
protected string clearBuffer = null; // Clear this if window size changes
protected void ClearConsole()
{
if (clearBuffer == null)
{
var line = "".PadLeft(Console.WindowWidth, ' ');
var lines = new StringBuilder();
for (var i = 0; i < Console.WindowHeight; i++)
{
lines.AppendLine(line);
}
clearBuffer = lines.ToString();
}
Console.SetCursorPosition(0, 0);
Console.Write(clearBuffer);
Console.SetCursorPosition(0, 0);
}
Console.SetCursorPosition(0, 0); //Instead of Console.Clear();
WriteTitle();
Console.WriteLine();
Console.WriteLine("Deleting:\t{0} of {1} ({2})".FormatString(count.ToString("N0")

Resources