I am a beginner in programming and it may seem a little funny to ask questions like this, but i have this code :
protected void OnSaveActionActivated (object sender, EventArgs e)
{
FileFilter filter = new FileFilter();
filter.Name = "Text files";
filter.AddPattern ("*.txt");
FileChooserDialog fcd = new FileChooserDialog ("... ?", this,
FileChooserAction.Save, "Cancel", ResponseType.Cancel, "OK", ResponseType.Accept);
if ((int)fcd.Run () == (int)ResponseType.Accept) {
System.IO.StreamWriter sw= new System.IO.StreamWriter(fcd.Filename);
sw.Write(textview1);
fcd.Filter = filter;
fcd.Destroy ();
} else {
fcd.Destroy ();
}
fcd.Destroy ();
Tho my Open file version works perfectly, I cant seem to make files to save properly into txt files, and i just dont understand anymore.
Sos :(
If textView1 is an actual control, then
sw.Write(textview1);
will not do what you want. Instead, try
sw.Write(textview1.Text);
which will write out the actual contents of the control, not the control itself.
Also, as #HighCore mentioned, it is much simpler to do
File.WriteAllText(file_path, textView1.Text);
Related
I have a program that scans in document bar codes and then allows for the user to click on a link which will open up a PDF associated with that bar code. My program works fine however I am running into a bug(?) in my code where every so often instead of opening the PDF once, the system will open it multiple times (5+) and it doesn't seem to be consistent. I'm hesitant to rewrite the code completely since it is actually working, it is simply inconvenient to have to close multiple windows. The method that I believe is causing the problem is below. Any help would be greatly appreciated as I am not sure where to start.
private void dgDisplay_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
id = (int)comboBox1.SelectedValue;
string ImagePath = getImagePath(id);
string filename = "";
if (e.ColumnIndex == 1)
{
filename = dgDisplay[e.ColumnIndex, e.RowIndex].Value.ToString();
filename = #ImagePath + filename + ".tif";
if (File.Exists(filename))
{
Process.Start(filename);
}
else
{
MessageBox.Show(filename);
}
}
}
To begin with, I'm relatively new to programming. I went through some introductory C# training for my new job, and it's the first language I've worked with.
I recently had a business problem that I decided to solve using C#, both to save time (I had hoped) and to learn more C# in the process. The business problem I mentioned was this: I had 600+ Word files that I needed to audit. For each document, I had to make sure that...
There was no text with strike-through anywhere in the document.
Track Changes was disabled.
There were no pending changes (as in changes that were made while
Track Changes was enabled and have yet to be accepted or
rejected).
There were no comments.
It would have been fastest to have my program iterate through all of the documents, making changes as it went along. But because of the nature of this assignment I wanted to make the changes manually, limiting the program's use to generating a list of files (out of the 600) where changes were necessary, and detailing what changes needed to be made for each of those files.
So, I have a button that calls up a FolderBrowserDialog.
private void AddFolderButtonClick(object sender, EventArgs e)
{
var folderBrowser = new FolderBrowserDialog();
if (folderBrowser.ShowDialog() != DialogResult.OK)
{
return;
}
this.progressBar1.Visible = true;
this.progressBar1.Style = ProgressBarStyle.Marquee;
this.Cursor = Cursors.WaitCursor;
var args = new List<string>(Directory.EnumerateDirectories(folderBrowser.SelectedPath));
// Get list of files in selected directory, adding to list of directories
args.AddRange(Directory.EnumerateFiles(folderBrowser.SelectedPath));
this.displayListBox.BeginUpdate();
foreach (string path in args)
{
if (File.Exists(path))
{
// This path is a file
this.ProcessFile(Path.GetFullPath(path));
}
else if (Directory.Exists(path))
{
// This path is a directory
this.ProcessDirectory((Path.GetFullPath(path)));
}
else
{
Console.WriteLine(Resources.Finder_Invalid_File_Or_Directory, path);
}
}
this.displayListBox.EndUpdate();
this.progressBar1.Visible = false;
this.progressBar1.Style = ProgressBarStyle.Continuous;
this.Cursor = Cursors.Default;
}
Together, the following two methods iterate through all subdirectories and files to create a full list of all files below the top level directory selected through the FolderBrowserDialog:
private void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
this.ProcessFile(fileName);
}
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
this.ProcessDirectory(subdirectory);
}
}
private void ProcessFile(string path)
{
Console.WriteLine(Resources.Finder_File_Processed, path);
string fileName = Path.GetFileName(path);
if (fileName == null || fileName.StartsWith(#"~$") || this.selectedFilesList.Contains(path))
{
return;
}
this.selectedFilesList.Add(path);
this.filePathsCountLabel.Text = (#"Count: " + this.selectedFilesList.Count);
this.displayListBox.Items.Add(path);
}
Once all this code has run, I get a full list of documents. I click a button and the program does what it's supposed to from here on out. Okay, cool. I mentioned before that half of the reason I chose to use C# to solve this was for the sake of learning. At this point I've got everything I need but what I really want to know is how can I implement threading to make the GUI responsive while the list of files is being generated? I've looked through several examples. They made sense. For some reason I just can't get my head around it for this application though. How can I make the whole process of processing subdirectories and files happen without locking up the GUI?
I believe what you need could be found here.
In short, to use a backgroundworker which does all the work on a separate thread thus prevents GUI freezes, first you instantiate BackgroundWorker and handle the DoWork event. Then you call RunWorkerAsync, optionally with an object argument.
As a skeleton code:
class myClass
{
static BackgroundWorker myBw = new BackgroundWorker();
static void Main()
{
myBw .DoWork += myBw_DoWork;
myBw .RunWorkerAsync ("an argument here");
Console.ReadLine();
}
static void myBw_DoWork (object sender, DoWorkEventArgs e)
{
// This is called on the separate thread, argument is called as e.Argument
// Perform heavy task...
}
}
You have to create a separate thread to process your work. Look at this if you are using .NET 4.0+ or this for older versions.
With Task, you can write
Task.Factory.StartNew(() => DoAction()
where DoAction is your function that starts to process data.
But do not forget to use Invoke, if you want to act with GUI from separate thread. For example, if you want to update some Label text from separate thread, you have to do this
label1.Invoke(() => label1.Text = "Some Text");
This is kinda strange, let me try to explain it as best as possible:
When I create a new file and Save it, it saves correctly (test.xml).
When I make changes to this file and Save it, it saves correctly (to test.xml)
When I make changes again to this file or just choose Save As, it works correctly (newtest.xml)
However, when I do a file open, make changes to a file (test.xml) and click Save it is saving to (newtest.xml).
This is in my MainForm.cs
if (this.openEditorDialog1.ShowDialog(this) == DialogResult.OK && editForm != null)
{
editForm.Close();
editForm = new EditorForm(this);
editForm.OpenFile(this.openEditorDialog1.FileName);
editForm.Closing += new CancelEventHandler(EditorForm_Closing);
editForm.MdiParent = this;
editForm.Show();
}
private void biFileSave_Click(object sender, EventArgs e)
{
if (!editForm.HasFileName)
{
if (this.saveEditorDialog1.ShowDialog(this) == DialogResult.OK)
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog1.FileName);
editForm.FileName = this.saveEditorDialog1.FileName;
}
}
else
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog1.FileName);
}
This is in my EditorForm.cs
public void OpenFile(string strFileName)
{
diagramComponent.LoadSoap(mainForm.openEditorDialog1.FileName);
this.FileName = mainForm.openEditorDialog1.FileName;
this.tabControl1.SelectedTab = DiagramTab;
}
I'm sure it has to do with the what I'm doing in the EditoForm but I can't seem to figure it out.
else
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog1.FileName);
It looks like you want:
this.ActiveDiagram.SaveSoap(editForm.FileName);
It must have to do with mainForm.openEditorDialog1.FileName. Use a FileName property of the form that does the saving. When you open the file, set the fileName to mainForm.openEditorDialog1.FileName. When you SaveAs, set the FileName property there, too. This way, whenever the current file, changes you set the FileName property appropriately. Then, when it comes time to save the file, you always have the correct filename.
In summary, only use the .FileName property of the SaveAs dialog or the FileOpen dialog right after you use them.
I want to be able to open a .txt file up into a richtextbox in c# and also into a global variable i have made called 'notes' but don't know how to do this. This is the code i have at the moment:
OpenFileDialog opentext = new OpenFileDialog();
if (opentext.ShowDialog() == DialogResult.OK)
{
richTextBox1.Text = opentext.FileName;
Globals.notes = opentext.FileName;
}
Only problem is it doesn't appear in neither the richtextbox nor in the global varibale, and the global allows it to be viewed in another richtextbox in another form. So please can you help, with ideally the .txt file going into both,
Thanks
Do you mean you want to have the text displayed or the filename?
richTextBox1.Text = File.ReadAllText(opentext.FileName);
Globals.notes = richTextBox1.Text;
You probably also want to correct this to:
if (opentext.ShowDialog() == DialogResult.OK)
In c# there are not global variables. The closest thing you can get is to make the variable "public static". But a better solution would be to make it an instance variable of an object you have access to, for example your main window class.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
FileName property of OpenFileDialog control just gives the full path of file selected by user. In order to read the content of this file, you will need to use a method like File.ReadAllText.
Try using this, I used it for a chat program and it works fine, you can set your timer rate to whatever you want. You also don't have to use a timer, you can have a button initiate the refresh of the rich text box.
private void refreshRate_Tick(object sender, EventArgs e)
{
richTextBox1.Text = File.ReadAllText(#"path.txt");
}
Hope this helps!
I hope, I am not late. It seems like there is something like:
OpenFileDialog opentext = new OpenFileDialog();
if (opentext.ShowDialog() == DialogResult.OK)
{
string selectedFileName = opentext.FileName;
richTextbox.LoadFile(selectedFileName, RichTextBoxStreamType.UnicodePlainText);
}
Refs
I develop a Winform Application with the framlework .NET 3.5 in C#.
I would like to allow the user to drag&drop a picture from Word 2007. Basically the user open the docx, select a picture and drag&drop them to my PictureBox.
I've already done the same process with picture files from my desktop and from Internet pages but I can't go through my problem with my Metafile. I've done few researches but I didn't find any solutions solving my issue.
Here is what I've done on my Drag&Drop event :
private void PictureBox_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.MetafilePict)){
Image image = new Metafile((Stream)e.Data.GetData(DataFormats.MetafilePict));
}
}
I can obtain a stream with this code : (Stream)e.Data.GetData(DataFormats.MetafilePict) but I don't know how to convert it into a Metafile or better an Image object.
If you have any idea or solution, I'll be glad to read it.
Thanks,
Here is a working example of Drag n Drop from Word (not for PowerPoint and Excel):
static Metafile GetMetafile(System.Windows.Forms.IDataObject obj)
{
var iobj = (System.Runtime.InteropServices.ComTypes.IDataObject)obj;
var etc = iobj.EnumFormatEtc(System.Runtime.InteropServices.ComTypes.DATADIR.DATADIR_GET);
var pceltFetched = new int[1];
var fmtetc = new System.Runtime.InteropServices.ComTypes.FORMATETC[1];
while (0 == etc.Next(1, fmtetc, pceltFetched) && pceltFetched[0] == 1)
{
var et = fmtetc[0];
var fmt = DataFormats.GetFormat(et.cfFormat);
if (fmt.Name != "EnhancedMetafile")
{
continue;
}
System.Runtime.InteropServices.ComTypes.STGMEDIUM medium;
iobj.GetData(ref et, out medium);
return new Metafile(medium.unionmember, true);
}
return null;
}
private void Panel_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.EnhancedMetafile) & e.Data.GetDataPresent(DataFormats.MetafilePict))
{
Metafile meta = GetMetafile(e.Data);
Image image = meta;
}
}
After this you can use image.Save to save picture or you can use it on picturebox or other control.
I think you need to call new Metafile(stream) as there is no method .FromStream in Metafile.
I'm still digging into he web to try different way to solve my issue.
Hopefully I've found this unanswered thread talking about my problem but without any response :
Get Drag & Drop MS Word image + DataFormats.EnhancedMetafile & MetafilePict :
http://www.codeguru.com/forum/showthread.php?t=456722
I work around with another io be able to copy floating Image (Image stored in Shape and not InlineShape) with Word 2003 and pasting into my winform. I can't paste the link of the second source (because of my low reputation on this website) but I'll do if someone request.
So apparently there are a common issue with the fact that you cannot access to your Metafile stored in the Clipboard and by Drag&Drop.
I still need to understand how to get my Metafile by Drag&Drop.