write textbox data to text file - text

I have code that is supposed to take all the user data that was input after the program was run and put it all into a text file.
Here is the code so far:
protected void WriteFile(object sender, EventArgs e)
{
FileStream fs = new FileStream(#"C:\Users\4567\MyDocuments\ExporterOutput.txt", FileMode.OpenOrCreate, FileAccess.Write);
TextBox[] tbs = { username, TextBox2, sgml, Path };
StringBuilder sb = new StringBuilder();
foreach (TextBox tb in tbs)
sb.AppendLine(tb.Text);
sb.AppendLine(DropDownList1.SelectedItem.ToString());
sb.AppendLine(DropDownList2.SelectedItem.ToString());
System.IO.File.WriteAllText(#"C:/Users/4567/My Documents/ExporterOutput.txt", sb.ToString());
I tried running it and the text file just shows up blank. Can anyone tell me what I am doing wrong and if there is an easier way to output all textbox information to a text file. And preferrable in a certain format.
Here is the edited code from the suggestions you gave me:
protected void WriteFile(object sender, EventArgs e)
{
TextBox[] tbs = { username, TextBox2, sgml, Path };
StringBuilder sb = new StringBuilder();
foreach (TextBox tb in tbs)
sb.AppendLine(tb.Text);
sb.AppendLine(DropDownList1.SelectedItem.ToString());
sb.AppendLine(DropDownList2.SelectedItem.ToString());
System.IO.File.WriteAllText(#"C:\\Users\\oZ012D\\My Documents\\ExporterOutput.txt", sb.ToString());
}

Ok, Im going to take a few guesses here.
Your last line should be
System.IO.File.WriteAllText(#"C:\\Users\\4567\\My Documents\\ExporterOutput.txt", sb.ToString());
You are using windows, so you need the "\" char and not the forward slash like you would on Linux. This is accomplished by having the double backslash (which c# recognizes as a single backslash) in your string.
Also, try getting rid of your first line. You are creating a file stream and then not using or closing it. I think its possible that the open FS is causing issues.
Don't worry about creation issues, the WriteAllText() call will create the file if it doesn't exist and will overwrite it if it does.
Let me know if that works, the only other thing that looks potentially incorrect to me is the way you are getting text from the drop down menus.

Related

How Can I paste the content of a text file 400 times

its for a unity research project, I dont want to have to press control v exactly 400 times. I just want to paste it in another .txt file
this is the text
http://pastebin.com/m1u4AFAr
Thank you for you help
Use Unity. Go to that link and copy the text. Run this script in Unity and it will duplicate the text for 400 times and save it. It will show you where it saved it. Any text you have in the clipboard will be duplicated 400 times.
void Start()
{
//Get Clipboard
string fileInfo = GUIUtility.systemCopyBuffer;
if (fileInfo == null)
{
Debug.Log("Clipboard is Empty. Exited");
return; //exit
}
//Multiply by file 400
System.Text.StringBuilder crazyfileX400 = new System.Text.StringBuilder();
for (int i = 0; i < 400; i++)
{
crazyfileX400.Append(fileInfo).Append("\r\n");
}
string filename = Application.persistentDataPath + "/" + "crazyFile.txt";
System.IO.File.WriteAllText(filename, crazyfileX400.ToString());
Debug.Log("File written to " + filename);
}
Have a look at this open source macro-creation and automation software.
You can use it to write a script that does the job for you. Here's a a script for simple copy and paste:
#c::
Send, {CTRLDOWN}c{CTRLUP}{ALTDOWN}{TAB}{ALTUP}
sleep, 300
Send, {CTRLDOWN}v{CTRLUP}{ENTER}{ALTDOWN}{TAB}{ALTUP}
return
You could adapt it to your situation by adding a loop.

StreamWriter trouble writing doubles to .txt file (C++)

I'm trying to write some double values to a text file the user creates via a SaveFileDialog, but everytime I do a streamWriterVariable->Write(someDoubleVariable), I instead see some kind of weird ASCII character in the text file where the double should be (music note, |, copyright symbol, etc). I'm opening the file with notepad if it's that of any significance. A basic outline of my code:
SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;
saveFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1->Title = "Save File Here";
saveFileDialog1->RestoreDirectory = true;
if (saveFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
FileInfo ^fleTest = gcnew FileInfo(saveFileDialog1->FileName);
StreamWriter ^sWriter = fleTest->CreateText();
sWriter->AutoFlush = true;
double test = 5.635; //Some arbitrary double I made up for test purposes
sWriter->Write(test);
sWriter->Flush();
sWriter->Close();
}
Thanks for your help!
Have you tried to set the encoding explicitly?
StreamWriter^ sWriter = gcnew StreamWriter(saveFileDialog1->FileName, false, System::Text::Encoding::ASCII);
The code you've provided does exactly what you ask it to, that is to write a double to the file in the internal computer format. What you most likely want it to write out the textual representation of the double.
In other words you should try sWriter->Write(test.ToString()) or some variation over this, to get the textual version of your double. This also applies to bool and most other variable representation.

Printing GMF diagrams using PDFCreator not able to open the generated pdf

I have implemented a direct printing to files of some GMF diagrams. The diagrams are opened, printed to file and the diagrams then closed. The issue I am facing is withing the following point:
private static void printDiagrams(IEditorPart editorPart,org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.SWTDiagramPrinter
diagramPrinter,String diagName) {
PrinterData printData = new PrinterData("winspool","PDFCreator");
if(printData!=null)
{
printData.printToFile = true;
printData.fileName = "D:\\"+diagName+".pdf";
printData.scope= 0;
final Printer printer = new Printer(printData);
diagramPrinter.setPrinter(printer);
diagramPrinter.setDisplayDPI(Display.getDefault().getDPI());
diagramPrinter.setFitToPage(true);
DiagramEditPart dgrmEP = ((DiagramEditor) editorPart).getDiagramEditPart();
assert dgrmEP != null;
diagramPrinter.setDiagrams(Collections.singletonList(((DiagramEditor) editorPart).getDiagram()));
diagramPrinter.run();
printer.dispose();
}
The issue is that with the above code I receive error during opening of pdf file. " Acrobat Reader could not open ... .pdf because it is either not supported file type or because the file has been damaged"
Tried also to put a sleep to be sure that printing is finished before disposing the printer. Same error in the end occured.
Any hint is helpful.
Figured it out that the generated file was not pdf at all , but prn file, intermediate files that a printer is storing before converting to final output. The after creating the prn files a conversion to the desired format is needed, in my case to pdf.
Hope this will help somebody also.
Cheers.

How does WPF OpenFileDialog track directory of last opened file?

As we know WPF OpenFileDialog no more changes the app's working directory and RestoreDirectory property is "unimplemented". However, upon subsequent open, its initial directory is default to the last opened file rather than the original working directory, so this information must be stored somewhere. I wonder is it possible to get/set it from user code?
On Windows 7 the recent file information is stored in the registry at this key:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Comdlg32\OpenSaveMRU
Beneath this key are subkeys for the various file extensions (e.g., exe, docx, py, etc).
Now, if you want to read these values, this will get a list of all paths stored beneath the subkeys (adapted from here):
String mru = #"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSavePidlMRU";
RegistryKey rk = Registry.CurrentUser.OpenSubKey(mru);
List<string> filePaths = new List<string>();
foreach (string skName in rk.GetSubKeyNames())
{
RegistryKey sk = rk.OpenSubKey(skName);
object value = sk.GetValue("0");
if (value == null)
throw new NullReferenceException();
byte[] data = (byte[])(value);
IntPtr p = Marshal.AllocHGlobal(data.Length);
Marshal.Copy(data, 0, p, data.Length);
// get number of data;
UInt32 cidl = (UInt32)Marshal.ReadInt16(p);
// get parent folder
UIntPtr parentpidl = (UIntPtr)((UInt32)p);
StringBuilder path = new StringBuilder(256);
SHGetPathFromIDListW(parentpidl, path);
Marshal.Release(p);
filePaths.Add(path.ToString());
}
References:
http://social.msdn.microsoft.com/Forums/zh/vcmfcatl/thread/bfd89fd3-8dc7-4661-9878-1d8a1bf62697
Getting the last opened file in fileopen dialog box
http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/c43ddefb-1274-4ceb-9cda-c78d860b687c)

The process cannot access the file 'd:\1.doc' because it is being used by another process

my code :
object c = "d:\\1.doc";
if(File.Exists(c.ToString()))
{
File.Delete(c.ToString());
}
error :
The process cannot access the file 'd:\1.doc' because it is being used
by another process.
How close ? with code
first of all use string instead of object, so:
string c = "d:\\1.doc";
now as the message indicated the file being used by another process. either by windows process, or you are opening the file stream and forget to close it. check in your code where you are interacting with the file.
Edit: Since you are using Microsoft.Office.Interop.Word make sure you close the file(s) open first like:
Word.ApplicationClass word = new Word.ApplicationClass();
//after using it:
if (word.Documents.Count > 0)
{
word.Documents.Close(...);
}
((Word._Application)word.Application).Quit(..);
word.Quit(..);
I had the same type of issue when I wanted to Delete File after Open/Read it using Microsoft.Office.Interop.Word and I needed to close my document and the application like that :
private void parseFile(string filePath)
{
// Open a doc file.
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document document = application.Documents.Open(filePath);
// Loop through all words in the document.
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
// Write the word.
string text = document.Words[i].Text;
Console.WriteLine("Word {0} = {1}", i, text);
}
// Close document correctly
((_Document)document).Close();
((_Application)application).Quit();
}
You have that file actively open in this or another program, and Windows prevents you from deleting it in that case.
Check if the file still running (opened) by another application
1- Microsoft Word
2- WordPad

Resources