How do you remove this text in vb net? - vb.net

Whenever I use streamwriter to put a textbox value into a .txt file it goes like this:
System.Windows.Forms.TextBox, Text: dadadadaad what is wrong here?
Dim Na_1 As New IO.StreamWriter(folder & "\name.txt")
Na_1.WriteLine(TextName)
Na_1.Close()

You have flush the StreamWriter before you close it:
Na_1.Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
Source: MSDN
So this should be your code:
Na_1 As New IO.StreamWriter(folder & "\name.txt")
Na_1.WriteLine(TextName)
Na_1.Flush()
Na_1.Close()
Alternatively you can use the Using-statement which automatically flushes and closes the stream (this is the better practice):
Using Na_1 As New IO.StreamWriter(folder & "\name.txt")
Na_1.WriteLine(TextName)
End Using
Following the comments of Ric and ForkAndBeard I think I misunderstood the problem:
Your problem is that you are calling the TextNameobject of the TextBox-Class directly via Na_1.WriteLine(TextName).
Now since you can't write an object to a file, the runtime simply call the ToString()-method of the Class TextBox which inherits from Object.
The result will be following:
"System.Windows.Forms.TextBox, Text: "
or generally:
"YourNamespace.YourClass"
Source:MSDN
If you want to have the text of the TextBox, you have to call the property TextBox.Text of the object:
Na_1.WriteLine(TextName.Text);

Related

How to append Text at the begining of a file?

I'm using the command IO.File.AppendAllLines("3.txt", "text", System.Text.Encoding.Default)
to write to 3.txt.
But the string is writing in down.
How I can write a string upper?
Call the strings ToUpper method to make the string upper case
IO.File.AppendAllLines("3.txt", "text".ToUpper(), System.Text.Encoding.Default)
The .Append() method will always append(add) the given string to an existing content. so n this case you cannot do like this.
I suggest you to read the content first, write the content back to the file along with the additional string. If you are expecting this, then the following code will help you:
var currentContent= File.ReadAllText(#"D:\3.txt");
File.WriteAllText(#"D:\3.txt", "Some string" + currentContent);
// here you are adding "Some string" at the begining of the file

Winrt StreamWriter & StorageFile does not completely Overwrite File

Quick search here yielded nothing. So, I have started using some rather roundabout ways to use StreamWriter in my WinRT Application. Reading works well, writing works differently. What' I'm seeing is that when I select my file to write, if I choose a new file then no problem. The file is created as I expect. If I choose to overwrite a file, then the file is overwritten to a point, but the point where the stream stops writing, if the original file was large, then the old contents exist past where my new stream writes.
The code is as such:
public async void WriteFile(StorageFile selectedFileToSave)
{
// At this point, selectedFileToSave is from the Save File picker so can be a enw or existing file
StreamWriter writeStream;
Encoding enc = new UTF8Encoding();
Stream dotNetStream;
dotNetStream = await selectedFileToSave.OpenStreamForWriteAsync();
StreamWriter writeStream = new StreamWriter(dotNetStream, enc);
// Do writing here
// Close
writeStream.Write(Environment.NewLine);
await writeStream.FlushAsync();
await dotNetStream.FlushAsync();
}
Can anyone offer clues on what I could be missing? There are lots of functions missing in WinRT, so not really following ways to get around this
Alternatively you can set length of the stream to 0 with SetLength method before using StreamWriter:
var stream = await file.OpenStreamForWriteAsync();
stream.SetLength(0);
using (var writer = new StreamWriter(stream))
{
writer.Write(text);
}
Why not just use the helper methods in FileIO class? You could call:
FileIO.WriteTextAsync(selectedFileToSave, newTextContents);
If you really need a StreamWriter, first truncate the file by calling
FileIO.WriteBytesAsync(selectedFileToSave, new byte[0]);
And then continue with your existing code.

Instantiating a function

This question is about a different instance that im trying to instantiate...
I have to get the "Read" function from my Cardreader class and return a string to it on the form1.vb .... Now i did what i can remeber but for some reason i'm having a problem with the brackets.... What can i do to fix this?
Form1.vb
ThisATM.getCardReader.Readr("TEST TEXT IS FUN")
CardReader.vb
Public Function Readr(ByVal card As KeyCard) As String
Return Read
End Function
Link for the image of the card reader function. I thought this link of the image of the code would be easier to understand.
The Readr function takes an KeyCard as parameter, not an string. So it seems like you have to create an instance to an KeyCard and use that as a parameter instead. In the code in the image you provided you are creating a keycard object, it seems like you should use that object in the Readr function like this:
Dim ThisKeyCard as new KeyCard("1234","5678","Mikki Monster")
Dim returnString as string=ThisATM.getCardReader.Readr(ThisKeyCard)

Out of memory exception while loading images

I am using the following piece of code to load images as thumbnails to a FlowLayoutPanel control. Unfortunately i get an OutOfMemory exception.
As you already guess the memory leak is found at line
Pedit.Image = System.Drawing.Image.FromStream(fs)
So how could i optimize the following code?
Private Sub LoadImagesCommon(ByVal FlowPanel As FlowLayoutPanel, ByVal fi As FileInfo)
Pedit = New DevExpress.XtraEditors.PictureEdit
Pedit.Width = txtIconsWidth.EditValue
Pedit.Height = Pedit.Width / (4 / 3)
Dim fs As System.IO.FileStream
fs = New System.IO.FileStream(fi.FullName, IO.FileMode.Open, IO.FileAccess.Read)
Pedit.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
fs.Dispose()
Pedit.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom
If FlowPanel Is flowR Then
AddHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
AddHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
AddHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
End If
FlowPanel.Controls.Add(Pedit)
End Sub
Update: The problem occurs while loading a number of images (3264x2448px at 300dpi - each image is about 3Mb's)
Documentation for Image.FromFile (which is related to your FromStream) says that it will throw OutOfMemoryException if the file is not a valid image format or if GDI+ doesn't support the pixel format. Is it possible you're trying to load an unsupported image type?
Also, documentation for Image.FromStream says that you have to keep the stream open for the lifetime of the image, so even if your code loaded the image you'd probably get an error because you're closing the file while the image is still active. See http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx.
Couple of thoughts:
First off, as Jim has stated, when using Image.FromStream the stream should remain open for the lifetime of the Image as remarked on the MSDN page. As such, I would suggest to copy the contents of the file to a MemoryStream, and use the latter to create the Image instance. So you can release the file handle asap.
Secondly, the images you're using are rather big (uncompressed, as they would exist in memory, Width x Height x BytesPerPixel). Assuming the context you use them in might allow for them to be smaller, consider resizing them, and potentially caching the resized versions somewhere for later use.
Lastly, don't forget to Dispose the image and the Stream when they are no longer needed.
You can solve this in a few steps:
to get free from the File-dependency, you have to copy the images. By really drawing it to a new Bitmap, you can't just copy it.
since you want thumbnails, and your source-bitmaps are rather large, combine this with shrinking the images.
I had the same problem. Jim Mischel answer led me to discover loading an innocent .txt file was the culprit. Here's my method in case anyone is interested.
Here's my method:
/// <summary>
/// Loads every image from the folder specified as param.
/// </summary>
/// <param name="pDirectory">Path to the directory from which you want to load images.
/// NOTE: this method will throws exceptions if the argument causes
/// <code>Directory.GetFiles(path)</code> to throw an exception.</param>
/// <returns>An ImageList, if no files are found, it'll be empty (not null).</returns>
public static ImageList InitImageListFromDirectory(string pDirectory)
{
ImageList imageList = new ImageList();
foreach (string f in System.IO.Directory.GetFiles(pDirectory))
{
try
{
Image img = Image.FromFile(f);
imageList.Images.Add(img);
}
catch
{
// Out of Memory Exceptions are thrown in Image.FromFile if you pass in a non-image file.
}
}
return imageList;
}

how to save/restore a form and controls between program runs?

I have a complex form to allow the user to configure my app.
What's the best way to save the form state & reload when the program next runs.
I mean text he has entered in list boxes, the selected item of combo/list/radio, whether a checkbox is cheeked, etc
Lots of people here telling me when to save, but not many telling me how ...
In the end I went with WritePrivateProfileString()
You have a few options of where to save the entered settings - in a configuration file, or in the registry, maybe a database (maybe even "the cloud", but i won't go there).
You should have the user carry out a specific action (such as clicking an Apply button) before you save the settings - you shouldn't just save the settings when the user closes the form, as that is ultimately not good UX.
How you persist the settings is totally up to you - you can save them into a straight name/value pair style config file, you may want to use XML in the config file, or you save them as keys and values in a known spot in the registry (or you could save name/value pairs into a database table).
When your application is next run, one of the start up tasks can be to check the known location (whether it be the registry or a config file) for the settings, and then load them into a settings class. Make sure that you have logical default values for each setting in case it has either never been set, or for some reason you cannot read it back in. The settings class can then either be passed in to each form for it to apply whatever settings are relevant, or it could be a static class (globally visible single instance class) so that it can just be read from anywhere in the application.
Edit: after reading your comment to another answer, here is another option, slightly more advanced. Use the settings class i mentioned earlier, but also use binding - you can bind your settings object directly to your form, so any values entered will be updated directly into the settings object without you having to write code to do it (provided you use two way binding). The "streaming" can be achieved by serializing the settings object to a file (or a database), i suggest you look at the XmlSerializer.
Serialize the Form.
Implement ISerializable, and in serializable constructor and GetObject() method load/save your fields.
In OnClosing serialize the form.
///
/// try to obtain the las serialized main form with old data
MainForm mainForm = DeserializeMainForm("mainForm.data");
///
/// if any old data found, create a new(empty) main form
if (mainForm == null) mainForm = new MainForm();
static MainForm DeserializeMainForm(string filePath)
{
MainForm mf = null;
FileStream fileStream = null;
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
fileStream = new FileStream(filePath, FileMode.Open);
mf = (MainForm)binaryFormatter.Deserialize(fileStream);
}
catch { }
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
return mf;
}
MainForm:
[Serializable]
public partial class MainForm : Form, ISerializable
{
protected MainForm(SerializationInfo info, StreamingContext context)
: this()
{
if (info == null)
throw new System.ArgumentNullException("info");
this.tbxServerIp.Text = info.GetString("server ip");
this.tbxServerPort.Text = info.GetString("server port");
this.tbxEventFilter.Text = info.GetString("event filter");
this.tbxWallId.Text = info.GetString("wallId");
foreach (Control control in this.Controls)
{
if (control is EventSender)
{
EventSender eventSender = (control as EventSender);
eventSender.LoadFromSerializationInfo(info);
}
}
}
private void SerializeThis()
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = new FileStream("mainForm.data", FileMode.Create);
try
{
binaryFormatter.Serialize(fileStream, this);
}
catch
{
throw;
}
finally
{
fileStream.Close();
}
}
protected override void OnClosing(CancelEventArgs e)
{
SerializeThis();
base.OnClosing(e);
}
}
Private Sub frm_Closing (sender as Object, e as CancelEventArgs) Handles MyBase.Closing
' save all the values you want'
End Sub
Private Sub frm_Load(sender as Object, e as EventArgs) Handles MyBase.Load
If SaveSettingsExist Then
' restore all the values you want'
End If
End Sub
I actually have a couple of generic routines I use like this for saving the form size/position and ListView column settings. So I have something like...
Private Sub frm_Closing (sender as Object, e as CancelEventArgs) Handles MyBase.Closing
SaveFormPos(Me)
SaveListview(Me, lvuInvoices)
End Sub
Private Sub frm_Load(sender as Object, e as EventArgs) Handles MyBase.Load
RestoreFormPos(Me)
RestoreListview(Me, lvuInvoices)
End Sub
The Me parameter (for the Listview routine) is used to create a key for the values to be saved to the registry. You have all sorts of options in front of you. You could put this functionality into a base class for all your Forms, create a SaveState class, or simply stick routines into a Module. You could save this data to the registry, a database, text files. You could have a generic routine that trawls through the Controls collection looking for TextBoxes, Checkboxes etc.
However, once you've created a useful set of save routines, you can then employ them on any subsequent form you want, so you only need to do the hard work once.
I also agree on having a LoadSettings/SaveSettings set of functions that are called when creating the form/ when closing the application.
As a store location for the application's settings I recommend using the Isolated Storage.
As an addition, depending on the controls you are using on your form, you could have the options of saving their status in XML format format and then restoring it next time.
For example Infragistics controls offer this possibility(e.g UltraDockManager, UltraToolbarManager have a SaveAsXml/LoadFromXml pair of functions).
You can somehow save everything in a hidden textbox in a hidden form.
When the user clicks the apply button, open the text file automatically and make the program read it line by line.
Example:
Line 1 could be the location of an image
Line 2 could be the text for a textbox
Line 3 could be a word or number that the program uses to determine if a
checkbox is true or false