I've been trying to figure out how to use the SaveFileDialog function in c# to save more than one file at a time.
The basic idea is, after the user has set parameters for a .cfg file, the user types out a set of serial numbers for which to save the configuration as. Then a SaveFileDialog is called allowing the user to save the one .cfg file under the names of the serial numbers the user listed.
Is this possible to do? Do you need to put the function into a loop, or is there another way to achieve this goal?
the .cfg file is set up like:
timezone=1
auto_DST=1
location=0
alarm_time=21
alarm_seconds_P=0
etc.
Here is what I have so far for saving that file:
List<Parameter> _paramList = new List<Parameter>();
List<Information> _infoList = new List<Information>();
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.DefaultExt = ".CFG";
saveFileDialog1.FileName = ( "config_" + txtParamValue.Text);
saveFileDialog1.Filter = "Configuration files (*.CFG)|*.CFG|All files (*.*)|*.*";
if ( saveFileDialog1.ShowDialog( ) == DialogResult.OK )
{
using ( StreamWriter objWriter = new StreamWriter( saveFileDialog1.FileName ) )
{
foreach (Parameter p in _paramList)
{
String name = p.ParameterName.Trim();
String val = p.ParameterValue.Trim();
foreach (Information i in _infoList)
{
if (p.ParameterName.Trim() == i.SimpleName)
{
name = i.InfoName;
if (i.InputChoice == "1")
{
if (p.ParameterValue == "On")
val = "1";
else
val = "0";
}
break;
}
else if (p.ParameterName.Trim() == i.InfoName)
{
if (p.ParameterValue == "On")
val = "1";
else
val = "0";
break;
}
}
if (name == "location" && val != location_update)
{
name = "location_update";
}
objWriter.WriteLine(name + "=" + val);
}
objWriter.Close();
}
}
Related
I have created 3 multi-line textboxes and I would like to write and save them to a .txt file. For example if I enter to my first textbox "John" on the first line and "Sakura" on the second line. Then if I enter "Bill" on the first line and "Sasuke on the second" to my second multi-line textbox and the same kind of text to my third textbox. I have a button to save it to a file. I would like the information in the text file to be shown as this:
This is what I have so far.
Hope my question is clear.
private void btn_Text1_Click(object sender, EventArgs e)
{
SaveFileDialog SaveFileDialog = new SaveFileDialog();
SaveFileDialog.Title = "Save As";
SaveFileDialog.Filter = "Text File (*.txt)|*.txt";
SaveFileDialog.InitialDirectory = #"C:\";
if (SaveFileDialog.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(SaveFileDialog.FileName, FileMode.Create);
using (StreamWriter objWriter = new StreamWriter(fs))
{
objWriter.WriteLine("Names: ");
objWriter.WriteLine(txt_FName.Text);
objWriter.WriteLine("-------------------");
objWriter.WriteLine("Last Names: ");
objWriter.WriteLine(txt_LName.Text);
objWriter.WriteLine("-------------------");
objWriter.WriteLine("Date of Birth: ");
objWriter.WriteLine(txt_Date.Text);*/
MessageBox.Show("SAVED");
}
}
}
Here's some very crappy code you can start from:
static void Main(string[] args)
{
string textBox1_Text = "";
string textBox2_Text = "";
string textBox3_Text = "";
var list1 = textBox1_Text.Split(Environment.NewLine.ToCharArray()).ToList();
var list2 = textBox2_Text.Split(Environment.NewLine.ToCharArray()).ToList();
var list3 = textBox3_Text.Split(Environment.NewLine.ToCharArray()).ToList();
var largestListSize = list1.Count > list2.Count ? list1.Count : list2.Count;
largestListSize = list3.Count > largestListSize ? list3.Count : largestListSize;
var sb = new StringBuilder();
for (int i = 0; i < largestListSize; i++)
{
var list1Line = list1.Count <= i ? list1[i] : string.Empty;
var list2Line = list1.Count <= i ? list2[i] : string.Empty;
var list3Line = list1.Count <= i ? list3[i] : string.Empty;
sb.AppendFormat(#"""{0}""\t""{1}""\t""{2}""", list1Line, list2Line, list3Line);
}
System.IO.File.WriteAllText("your_path", sb.ToString());
}
A simple answer would be something like this:
private void Button1Click(object sender, EventArgs e) {
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "Save As";
saveFileDialog.Filter = "Text File (*.txt)|*.txt";
saveFileDialog.InitialDirectory = #"C:\";
if (saveFileDialog.ShowDialog() == DialogResult.OK) {
FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create);
using (StreamWriter objWriter = new StreamWriter(fs)) {
for (int i = 0; i < GetMaxRows(); i++) {
objWriter.WriteLine("\"{0}\"\t\"{1}\"\t\"{2}\"", GetText(i, 0), GetText(i, 1), GetText(i, 2));
}
}
MessageBox.Show("SAVED");
}
}
private int GetMaxRows() {
return Math.Max(Math.Max(textBox1.Lines.Length, textBox2.Lines.Length), textBox3.Lines.Length);
}
private string GetText(int row, int textboxId) {
switch (textboxId) {
case 0:
return textBox1.Lines.Length > row ? textBox1.Lines[row] : string.Empty;
case 1:
return textBox2.Lines.Length > row ? textBox2.Lines[row] : string.Empty;
case 2:
return textBox3.Lines.Length > row ? textBox3.Lines[row] : string.Empty;
default:
throw new Exception("Not a valid id");
}
}
But it looks like you are trying to save this in tab separated format. And the problem is when you write: '20" monitor' into the field and you get a "-sign in the middle. Perhaps the tab is enough as a separator?
This answer is just to fix the problem you mention, getting text from all textboxes like your output file. But i think you should try to find a better way to do this (perhaps a datagrid as suggested), and then solve the problems with invalid characters. Example for saving from datagrid: Exporting from a dataset to a tab delimited file
There are easier ways to save to a tab seperated file even with text delimiters and support for escaping characters that are invalid.
But since i dont know how this is going to be used i am just giving you a simple answer to your question, hope it helps.
ok what im trying to do is load a text file search it for a certain string if the string exists then it will will disable button
if it don't exist it will Wright to the file
if (File.Exists(hostfile))
{
{
string s = "elfenliedtopfan5 programupdate";
string file = hostfile;
List<string> lines = new List<string>(System.IO.File.ReadAllLines(file));
int index = lines.FindLastIndex(item => item.Contains("elfenliedtopfan5 programupdate"));
if (index != -1)
{
lines.Insert(index + 1, s);//""
}
// System.IO.File.WriteAllLines(file, lines);
MessageBox.Show("text test 1 found");
}
}
else
{
DialogResult dialogResult = MessageBox.Show("text not found would you like to add it ", "Text Not Found", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
using (StreamWriter sw = File.AppendText(hostfile))
{
sw.WriteLine("elfenliedtopfan5 update");
sw.Close();
messagebox.show("done");
}
}
}
but even know it does exist it will add it again and im confused to why this is the case any help would be appropriated
elfenliedtopfan5
Here is a simple way to read from or write to a text file:
string filename=#"D:\file.txt";
string value="your value"
var content = System.IO.File.ReadAllText(filename);
if (content.Contains(value))
this.Button1.Enabled = false;
else
System.IO.File.AppendAllLines(filename, new string(){value} );
i am trying to upload documents .user can be able to upload theri documents but he/she can be upload images istead of documents and i want to d restrict about this how to apply condition this is my upload code
if (FileUploadControl.PostedFile != null &&
FileUploadControl.PostedFile.ContentLength
> 0)
{
if
(FileUploadControl.FileContent.Length < 100000)
{
string filename =
Path.GetFileName(FileUploadControl.PostedFile.FileName);
string folder = Server.MapPath("~/Docfiles/");
Directory.CreateDirectory(folder);
FileUploadControl.PostedFile.SaveAs(Path.Combine(folder, filename));
try
{
cc.upload1(Txt_docde.Value, txt_dname.Value,
FileUploadControl.FileName, Convert.ToInt32(Docdrop.SelectedValue),
Convert.ToInt32(DropDownList2.SelectedValue),
Convert.ToString(Session["Login2"]),Convert.ToInt32(Session["UserID"]));
StatusLabel.ForeColor = System.Drawing.Color.Green;
//StatusLabel.ForeColor = System.Drawing.FontStyle.Bold;
StatusLabel.Text = "Success";
}
catch
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "Failed";
}
}
else
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "File Size to big";
}
}
Make generic list of extensions you want to allow and then check if file you are trying to upload meets that extension requirement.
var allowedExtensions = new string[] { "doc", "docx", "pdf" };
var extension = Path.GetExtension(FileUploadControl.PostedFile.FileName).ToLower().Replace(".", "");
if (allowedExtensions.Contains(extension))
{
// Good to go
}
Here is full code for you
if (FileUploadControl.PostedFile != null && FileUploadControl.PostedFile.ContentLength > 0)
{
var allowedExtensions = new string[] { "doc", "docx", "pdf" };
var extension = Path.GetExtension(FileUploadControl.PostedFile.FileName).ToLower().Replace(".", "");
if (FileUploadControl.FileContent.Length < 100000 && allowedExtensions.Contains(extension))
{
string filename =
Path.GetFileName(FileUploadControl.PostedFile.FileName);
string folder = Server.MapPath("~/Docfiles/");
Directory.CreateDirectory(folder);
FileUploadControl.PostedFile.SaveAs(Path.Combine(folder, filename));
try
{
cc.upload1(Txt_docde.Value, txt_dname.Value, FileUploadControl.FileName, Convert.ToInt32(Docdrop.SelectedValue), Convert.ToInt32(DropDownList2.SelectedValue), Convert.ToString(Session["Login2"]),Convert.ToInt32(Session["UserID"]));
StatusLabel.ForeColor = System.Drawing.Color.Green;
StatusLabel.Text = "Success";
}
catch
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "Failed";
}
}
else
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "File Size to big";
}
}
Try something like this to validate the file type suffix that you are interested in:
if (string.Equals(fileExt, ".pdf", StringComparison.OrdinalIgnoreCase)) {...}
You need to either check the extension of the posted file or its MIME type to detect whether it's the right format.
Go get the MIME type, check the ContentType property.
ASP.NET How to get MIME Type
If you want to look for a specific file type you can use the Path.GetExtension method.
string fileExtension = Path.GetExtension(filename);
if (fileExtension == ".doc") //or whatever file type your looking for
{
try
{ do your work }
}
In the next javascript code i have a function to open a file(xml) and then it will search for all the occurences that are between a specific tag(<file>). After using a Regex expression to get the filenames, i need that the dialog can be open, automatically, the same number of times of the files discovered in the xml file. The objective is to force the user to search in their local directory for the files that are in the xml file. After this i will send the strings to the server side.
function fileSelected(evt) {
var files = evt.target.files;
var reader = new FileReader();
var bol;
if (document.getElementById("fileToLoad").value == "") {
alert("Please select a file before submitting.");
bol = 0;
}
else {
ext = document.getElementById("fileToLoad").value;
fpath = ext;
ext = ext.substring(ext.length - 3, ext.length);
ext = ext.toLowerCase();
if (ext == 'xml')
bol = 1;
else if (ext == 'rdf')
bol = 1;
else {
alert("You selected a ." + ext + " file; this is not allowed.");
bol = 0;
}
}
if (bol == 1) {
reader.onload = function (event) {
editor.setValue(event.target.result);
var teste = editor.getValue();
getFileName(teste);
var debug = event.target.files;
document.getElementById("Procura").style.visibility = "visible";
//document.getElementById('<%=hf.ClientID%>').value = editor.getValue();
}
reader.readAsText(files[0], "UTF-8");
}
return false;
}
function getFileName(str) {
var matches = str.match(/<file>(.*)<\/file>/g);
var len = matches.length, i, result;
for (i = 0; i < len; i++) {
matches[i] = matches[i].replace(/<[\/]{0,1}(file|FILE)[^><]*>/g, "");
//need to open dialog for user to search for the same file in matches[i]
//after get file, will save on a string in order to send to server
}
}
I´ve tried many things but this is my first steps in this world(js/jquery/html).
I have an application in which the user interacts with a database and prepares a report of what he needs. The item prices are listed in the database. Once he chooses the items then he generates a report in Excel format. When he hits the Generate a Report button, he is asked where to save the report. These are all good. The problem is that when he saves the report and hits the Generate A Report button, he is able to save the same file with the same name at the same location when a file of the same name exists at that location. It basically replaces the old one. I wrote a code to check for the file if it exists and it works but the problem is that it does not appear at the instant when you are saving the file. It appears before. What I want is when I try to save the file at any location, it gives me at that instant that "The file exists and do you want to replace it with it", more like Windows dialog when you try to save a word document into a location where there is a document with the same name.
If anyone needs any clarifications please comment, I am online most of the times.
Here is the code
private void btnRunReport_Click(object sender, EventArgs e)
{
if (cmbReportsList.SelectedIndex != -1)
{
_qry = new QueryMgt();
OpenProjectDb();
string _sProjectName = (dbManager.ExecuteScalar(CommandType.Text, _qry.GetProjectFileName())).ToString();
CloseProjectDb();
if (cmbReportsList.SelectedIndex == 0)
{
SaveFile.Filter = "excel 2007 (*.xlsx)|*.xlsx";
SaveFile.DefaultExt = "xlsx";
SaveFile.FileName = _sProjectName + " Report1";
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (SaveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.Text = System.IO.Path.GetFileName(SaveFile.FileName);
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (strFilepath.Length > 218) { strFilepath = StringMgt.Left(strFilepath, 218); }
btnRunReport.Visible = false;
bg1804Rpt.RunWorkerAsync();
Application.DoEvents();
}
}
else if (cmbReportsList.SelectedIndex == 1)
{
SaveFile.FileName = _sProjectName + " Report2";
SaveFile.Filter = "excel 2007 (*.xlsx)|*.xlsx";
SaveFile.DefaultExt = "xlsx";
if (SaveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//SaveFile.FileName = "Report2";
this.Text = System.IO.Path.GetFileName(SaveFile.FileName);
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (strFilepath.Length > 218) { strFilepath = StringMgt.Left(strFilepath, 218); }
btnRunReport.Visible = false;
bgMCRpt.RunWorkerAsync();
Application.DoEvents();
}
}
else if (cmbReportsList.SelectedIndex == 2)
{
_qry = new QueryMgt();
_formula = new FormulaMgt();
string sSQL;
string chrCountryName = "";
OpenProjectDb();
OpenTableDb();
DataSet dsProjectSpec;
DataSet dsCountry;
sSQL = _qry.GetProjectSpec().ToString();
dsProjectSpec = dbManager.ExecuteDataSet(CommandType.Text, sSQL);
sSQL = _qry.GetCountry().ToString();
dsCountry = dbManagerTable.ExecuteDataSet(CommandType.Text, sSQL);
foreach (DataRow row in dsCountry.Tables[0].Select("pk_lngCountryID ='" + dsProjectSpec.Tables[0].Rows[0]["lngCountryId"] + "'"))
{
chrCountryName = row["chrCountryName"].ToString();
break;
}
SaveFile.FileName = _sProjectName + " Report3";
SaveFile.Filter = "excel 2007 (*.xlsx)|*.xlsx";
SaveFile.DefaultExt = "xlsx";
// SaveFile.Filter = "Microsoft Office Excel Worksheet (*.xlsx)|*.xls|All files (*.*)|*.*";
if (SaveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//SaveFile.FileName = "Report3";
this.Text = System.IO.Path.GetFileName(SaveFile.FileName);
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (strFilepath.Length > 218) { strFilepath = StringMgt.Left(strFilepath, 218); }
btnRunReport.Visible = false;
bgMDRpt.RunWorkerAsync();
Application.DoEvents();
}
}
}
else if (cmbReportsList.SelectedIndex == -1)
{
MessageBox.Show("Please select any report", "Info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
You have not provided any code so I am left wondering.
But are you using SaveFileDialog? If not, I highly suggest it. It provides that functionality.
SaveFileDialog sfd = new SaveFileDialog();
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Do Something
// Access the filename they choose via: ofd.FileName
}
And if the user selects a file that exists, they will be asked if they are sure they want to overwrite it.
SaveFileDialog also has several properties you can define. Such as the Filter property for defining acceptable file extensions.