I am developing an app right now that reads in data from a windows from and generates an XML file based on the input.
I am tasked with creating a new file each time the form is updated (User presses "Submit"). (so far so good)
Here is the catch: The file has to be named after a prominent field input. (If the user types '993388CX' in the text box, the app would rename the pending file 993388CX.xml).
I understand how to actually rename a file in C#, but not how to rename it based on a form's input. Do any classes/methods exist that will dynamically rename the file based on the form input?
Code:
//Reads info1 from user input on the app UI and generates XML statement
XTemp = XDoc.CreateElement("New_Info");
XTemp.InnerText = info1.Text;
Xsource.AppendChild(XTemp);
XDoc.Save(#"C:\oldfile.xml");
I need the new file to be renamed after the string in info1.Text
If the user input was "John5", the file needs renamed to john5.xml
Thank you
Either directly save it with the correct name:
XDoc.Save(String.Format("C:\\{0}.xml",info1.Text));
OR
Rename it afterwards
File.Move("c:\\oldfile.xml", String.Format("C:\\{0}.xml",info1.Text));
XDoc.Save(#"C:\" + info1.Text + ".xml");
File.Move should do what you want.
Related
How would I go about saving a user form input from a view to an existing text file with the ASP.NET MVC framework?
So to start of, you would accept some code from the user and then save it:
string userInput =Console.Readline();
Then you would use the code WriteAllText(). This allows you to create a new file and writes the contents to it. If the file already exists, it will be overwritten.
So basically:
string userInput =Console.Readline();
File.WriteAllText("thenameyouwanttogivetoyourfile.txt", userInput);
This reads the file and then outputs it
string readText = File.ReadAllText("thenameyouwanttogivetoyourfile.txt");
Console.WriteLine(readText);
Thats how you create a new file. To overwrite a file that already exists, you do the same thing but with the keyword Create(). This creates or overwrites a file and if you want to replace the contents of one file with another, use Replace().
For futher help try this link:
https://learn.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8
I currently have a program that merges a folder consisting of word docs into one combined file via user input with a FileBrowserDialog. Once files are selected, a 'combine' button applies the code shown below which sources the folder containing the documents, output location and name of the file created.
string fileDate = DateTime.Now.ToString("dd-MM-yy");
string fileTime = DateTime.Now.ToString("HH.mm.ss");
string outcomeFolder = outputFolder;
string outputFileType = ".docx";
string outputFile = "Combined Folder " + fileDate + " # " + fileTime + outputFileType;
string outputFileName = Path.Combine(outcomeFolder, outputFile);
// Combines the file name, output path selected and the yes / no for pagebreaks.
MsWord.Merge(sourceFiles, outputFileName, pageBreaker);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);}
The MsWord referenced calls a separate .CS file which combines the folder components, output name and a boolean to enable page-breaks. The MsWord also automatically saves the word .doc to the user specified location once the contents of the folder are successfully combined. MsWord.Merge(sourceFiles, outputFileName, pageBreaker);
The issue i'm wanting to address is, when I enable this check box:
if (convert2PDFBox.Checked)
Microsoft.Office.Interop.Word.Application officeApp = new Microsoft.Office.Interop.Word.Application();
officeApp.Documents.Open(outputFileName);
outputFileType = ".pdf";
officeApp.ActiveDocument.SaveAs(outputFileName + outputFileType, WdSaveFormat.wdFormatPDF);
officeApp.Quit();
I want the program to solely create a PDF of the combined folder and not 2 seperate .doc and .PDF files, which it currently does. Since the MsWord.save function is called separately and is essential to the overall function of my program, I was wondering is there a possibility of deleting the initially combined file once conversion of the PDF takes place? e.g. "combinedDocument".Delete - Essentially allowing the copy to take place however not presenting the user with the initial .doc - only the .PDF
Though the issue is small, I would love to get it addressed and welcome any suggestions or advice with this manner. I can also provide any additional information if needed, thank you.
tl;dr - merging program creates an amalgamated Word .doc, which i want to change solely to a PDF when a checkbox is enabled instead of creating a .doc and PDF.
I finally resolved my issue - What I decided to do was manipulate my existing MsWord.cs and create a separate PDF.cs call for my main form:
Rather than save the Word .doc when being merged, I instead used: wordApplication.ActiveDocument.SaveAs(outputFile, Word.WdSaveFormat.wdFormatPDF);
which saved the merged content thus far as a .pdf
This however presented errors with Microsoft Word as I was then prompted to 'Save File As' due to the merged file never actually being saved in a .Doc / .Docx format
I then altered the closing statement of the call,
// Close Word application
wordApplication.Quit(
false, // save changes
By setting the 'Save Changes' setting to False, it removed the 'Save As' prompt which allowed the Word doc. to be dismissed without needing to be saved, thus leaving only the initial PDF created. I then applied the two separate File type calls to each checkbox presented, which allowed the user to enable the outcome format of the merged files.
Thank you for the suggestions regarding the issue.
Sorry for the likely noobish question, just starting to learn c#, and couldn't find anything that worked.
I'm making a text editor in c#, and so far it can open and save text files from inside the program with dialogs, but how can I make it load the text from a file that I open in windows explorer, outside of the editor, with the editor
Basically, I can already read from text files opened inside the editor, but how can i make it so that if I open a text file (and have the default program for opening text files set to my editor), it'll read it?
I saw something about getting the filename somehow and passing it as an argument, if that helps.
If I understood you correctly, you want to pass the filename/names as command line arguments ?
If you look at the Main, which starts the program you can see that it will store parameters in a string[] (string array) so if you pass arguments you can just check the args[] inside the program to get the parameters you sent in. Please ask more if you need more help !
UPDATED
As per your request if you open a file from windows explorer it will send the path of the file it to the Main method. So lets say you right click a file and choose to open it with your text editor. You have to use the path as I do below, and read the file's content. Then you can do whatever you want with the content.
class TestClass {
static void Main(string[] args) {
// Now you have all arguments in the string array
if (args.Length != 0) {
string pathToTextfile = args[0];
}
StreamReader textFile = new StreamReader(pathToTextfile);
string fileContents = textFile.ReadToEnd();
textFile.Close();
}
}
So you have a text editor coded in C#, and you want to be able to open a text file through double clicking on the file in Windows explorer. If so, basically 2 steps:
1. Your editor program must accept one argument as the file name. Carl had already given an example.
2. You need to associate *.txt files with your text editor. This could be done through editing Windows registry. please check What registry keys are responsible for file extension association
You can use the OpenFileDialog class to select a file to show in your program.
I start my application from withint Visual Studio 2010.
I add then some files into my application and each file type`s icon like icon from doc,docx,xls,pdf etc are added as String/Bitmap key/value pair to my IconImages.Resx file via
private void DumpTempResourceToRealResourceFile(IDictionary<String, Bitmap> tempResource)
{
using (ResXResourceWriter writer = new ResXResourceWriter("IconImages.Resx"))
{
foreach (KeyValuePair<String,Bitmap> item in tempResource)
{
writer.AddResource(item.Key, item.Value);
}
writer.Generate();
}
}
When the icons are added to the resource I close the application.
Then I start my application again with VS 2010 and add some files within my document application. The file types are written again to my IconImages.Resx.
Then I close my application and check the IconImages.Resx file under the \bin\ folder and the previous saved images are gone and I have new/different ones now.
Why can I not say OPEN a .resx file and append stuff to it? Everytime I create a ResourceWriter object with the same name "IconImages.Resx" I overwrite the previous added stuff and thats stupid.
How can my IconImages.Resx file stay alive over an application session without being overwritten by other stuff I add?
I haven't used ResXResourceWriter, but usually *Writer classes simply write a data file from scratch.
If you want to "append" new data you would typically have to use a *Reader class to deserialise the existing data into memory, then merge/add in any new data you wish to, and use a *Writer object to then write the resulting data back out. Take a look at ResXResourceReader to see if it supports what you need to do this.
I am having now a lookup table "FiletypeImage" with the filetype ".docx" and the raw binary data aka blob. This table gets retrieved in my documentService and cached in a static variable. with a Get and Add method which are called by my DocumentListViewModel. Its very fast thx to sqlite :)
I have a FileUpload control (FileUpload1) on my web form, as well as a "Sumbit" button, a label, and a hidden field that contains a UserID. I have the following code in the button's click event:
string path = Server.MapPath("~/userfiles/");
if (FileUpload.HasFile)
{
try
{
FileUpload1.SaveAs(path + UserID.Value + "/image.jpg");
}
catch
{
Label1.Text = "* unable to upload file";
Label1.Visible = true;
}
}
It works great if I upload an actual file. However, if I type a non-existent filename (for example, "c:\a.jpg", which does not exist on my computer) into the FileUpload's textbox, and click the Sumbit button, HasFile still returns true. Furthermore, SaveAs() does not throw any exceptions, and it is a void function that returns no value indicating success or failure. How do I tell whether a file was actually uploaded?
Just check to see if it exists.
if(File.Exists(myFile)){
//it was uploaded.
}
You could check FileUpload.PostedFile.ContentLength property
You could check if the file exists using File.Exists before calling SaveAs.
Hmmm....
Not sure I understand. First, in your code, FileUpload.HasFile won't compile. If should be FileUpload1.HasFile.
When I correct this, and run your code, this line returns false if the file does not exist...
You can check if file exists after uploading using File.Exists(path); The file object is part of System.IO.
This is not about your actual question, but you should validate any user input, especially if you want users to upload files to a virtual folder on your webserver. You should at least check whether the content type of the file is the one you expect, or - even better, filter (resize) the image using the classes available in the .NET framework.
If you don't do so users may share arbitrary content via your site or place malicious files (e.g. images containing script which might get executed by certain web browsers) on your server.
With additional validation you will also be able to validate if there has actually been content sent.
AND: A really severe vulnerability opens up when you build the save path by concatenating input from a form field (I assume UserID.Value is the POST parameter you mention?). This allows users to decide where to store the content on your server, and, even worse, be able to overwrite existing files!!!