Replace SaveFileDialog to saving in code - c#

I have such code that saves bin file, but user has to choose file
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Binary File (*.bin)|*.bin";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
Question.PersistObject(questions, myStream);
myStream.Close();
}
}
But I want to choose file in code, and if a file with such name doesn't exist, then create it. How to set in myStream that file?

Replace all your logic related to the OpenFileDialog with File.Open:
using (var myStream = File.Open(someFilePath, FileMode.OpenOrCreate))
{
Question.PersistObject(questions, myStream); // do something with the stream
}
The OpenOrCreate file mode will open the file if it exists, or create it if it does not.
The using statement will take care of closing the stream for you.

One option would be to have a base name and append a number:
string templateName = "myfile{0}.bin";
string finalName;
int count = 0;
do {
finalName = String.Format(templateName, count++);
} while (File.Exists(finalName);
Or, if you don't care about the name, use Path.GetTempFileName
Then pass that name to StreamWriter:
using (StreamWriter writer = new StreamWriter(finalName))
{
// Write stuff
}

Related

objectListView (Export to csv)

I'm using DatasListView from OLV, and I want to export my data to csv.
They said to use olvexporter, but I can not find an example of it.
Can anyone explain how to use OlvExporter to me?
You can try this:
string csv = string.Empty;
var olvExporter = new OLVExporter(objectListView1,
objectListView1.FilteredObjects);
csv = olvExporter.ExportTo(OLVExporter.ExportFormat.CSV);
csv = csv.Replace(",", ";");
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.FileName = "ExportFile.csv";
saveFile.Filter = "csv files (*.csv)|*.csv";
if (saveFile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFile.FileName))
{
sw.Write(csv);
}
}
The second parameter at the OLVExporter is only necessary if you want to enable Filtering at your objectListView. It it's set you are only exporting the results after the filtering.
If you choose CSV as ExportFormat you can use the csv.Replace() to change the output at the csv file.
The SaveFileDialog is also not necessary.

How to save the file using save file dialog box

I want to save any type of file using save file dialog box...
My requirement is based upon the selection of list box(it contain various type of file like .txt,.xls) i want to provide download option using save file dialog box...if user got select .txt file the file store in text format based on the file extension i want to store file...Those file i want to save same to same file copy into the particular location
pl z help me
Dim digresult As DialogResult = MessageBox.Show("Do you want to download ? ", "View", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If digresult = Windows.Forms.DialogResult.Yes Then
downlddialog.Filter = "All files (*.*)|*.*"
downlddialog.Title = "Save a file"
downlddialog.RestoreDirectory = True
downlddialog.OverwritePrompt = True
downlddialog.ShowDialog()
Dim dr As String = downlddialog.FileName
You can pull out the file extension and then appropriate file writing logic for particular file extension see sample code below,
SaveFileDialog oSaveFileDialog = new SaveFileDialog();
oSaveFileDialog.Filter = "All files (*.*) | *.*";
if (oSaveFileDialog.ShowDialog() == DialogResult.OK)
{
string fileName = oSaveFileDialog.FileName;
string extesion = Path.GetExtension(fileName);
switch (extesion)
{
case ".txt"://do something here
break;
case ".xls"://do something here
break;
default://do something here
break;
}
}
System.Windows.Forms.SaveFileDialog saveFileDialog1;
saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
DialogResult dr= saveFileDialog1.ShowDialog();
if (dr==DialogResult.OK)
{
string filename = saveFileDialog1.FileName;
//save file using stream.
}
you can use this code this code is in C# instead of MessageBox.Show use System.Windows.Forms.SaveFileDialog
This will do the job...
the filter property is optional - it just if you want the user save a specific file type
VB:
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog ^ saveFileDialog1 = new SaveFileDialog();
saveFileDialog1->Filter =
"JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1->Title = "Save an Image File";
saveFileDialog1->ShowDialog();
// If the file name is not an empty string, open it for saving.
if(saveFileDialog1->FileName != "")
{
// Saves the Image through a FileStream created by
// the OpenFile method.
System::IO::FileStream ^ fs =
safe_cast<System::IO::FileStream*>(
saveFileDialog1->OpenFile());
// Saves the Image in the appropriate ImageFormat based on
// the file type selected in the dialog box.
// Note that the FilterIndex property is one based.
switch(saveFileDialog1->FilterIndex)
{
case 1 :
this->button2->Image->Save(fs,
System::Drawing::Imaging::ImageFormat::Jpeg);
break;
case 2 :
this->button2->Image->Save(fs,
System::Drawing::Imaging::ImageFormat::Bmp);
break;
case 3 :
this->button2->Image->Save(fs,
System::Drawing::Imaging::ImageFormat::Gif);
break;
}
fs->Close();
}
C#
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if(saveFileDialog1.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
switch(saveFileDialog1.FilterIndex)
{
case 1 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 2 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 3 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Gif);
break;
}
fs.Close();
}

Confusion in reading file using FolderBrowserDialog

which i used earlier (FileuploadControl tool used)
inside button click method
if (FileUploadControl.HasFile)
{
filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
string lines;
string root = Server.MapPath("~/");
string Template = root + filename;
using (StreamReader reader = new StreamReader(Template))
{
while ((lines = reader.ReadLine()) != null)
list.Add(lines); // Add to list.
}
//file is now in list
//MORE IMPORTANT CODE
}
But now I am just using FolderDialog
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog();
if (result == DialogResult.OK) {
textBox8.Text = folderDialog.SelectedPath;
Environment.SpecialFolder root = folderDialog.RootFolder
//...
}
How can i read the file so that i can only use the FolderBrowserDialog to read an entire file and extract data?
I guess you are working in Windows Forms now if you are using FolderDialog.
You should use better OpenFileDialog if you want the user to check a FILE, not a Folder.
You can read the file using System.IO classes once you have the path.
If the file is text for example you can do:
string FinalPath = OpenFileDialog.FileName;
string Text= System.IO.File.ReadAllText(FinalPath);
you can also read the file into byte()
byte[] file = System.IO.File.ReadAllBytes(FinalPath);

saving a file to a specific path

i have the code for saving a gridview as an html file using a savefiledialog. i want to save it to a specific path (without using the savefiledialog)... how can i do that?
here's my code:
SaveFileDialog dialog = new SaveFileDialog();
dialog.DefaultExt = "*.html";
dialog.Filter = "WORD Document (*.html)|*.html";
if (dialog.ShowDialog() == true)
{
RadDocument document = CreateDocument(rgvReportData);
document.LayoutMode = DocumentLayoutMode.Paged;
document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
document.Arrange(new RectangleF(PointF.Empty, document.DesiredSize));
document.SectionDefaultPageMargin = new Telerik.Windows.Documents.Layout.Padding(2, 2, 2, 2);
document.SectionDefaultPageOrientation = PageOrientation.Landscape;
HtmlFormatProvider provider = new HtmlFormatProvider();
using (Stream output = dialog.OpenFile())
{
provider.Export(document, output);
}
}
how can i sve it without using a savefiledialog?
using(StreamWriter output = new StreamWriter("path\to\your\file")) {
provider.Export(document, output);
}
will do the same thing, but to a specific path. You can read more on file access on MSDN.
String fileName = "youfilename.html"; // give the full path if required
RadDocument document = CreateDocument(rgvReportData);
document.LayoutMode = DocumentLayoutMode.Paged;
document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
document.Arrange(new RectangleF(PointF.Empty, document.DesiredSize));
document.SectionDefaultPageMargin = new Telerik.Windows.Documents.Layout.Padding(2, 2, 2, 2);
document.SectionDefaultPageOrientation = PageOrientation.Landscape;
HtmlFormatProvider provider = new HtmlFormatProvider();
Stream output = File.Open(filename, FileMode.Open, FileAccess.ReadWrite);
provider.Export(document, output);
}
using (var output = new FileStream("path", FileMode.Create, FileAccess.Write))
{
provider.Export(document, output);
}
OpenFileDialog displays the specific path that you have choosen.
You could set the path of the SaveFileDialog, is not necessary to show the dialog like dialog.ShowDialog(), you have just to set the path like dialog.Filename = "file name".
And replace it like :
SaveFileDialog dialog = new SavefileDialog();
dialog.FileName = "path"; // like "C:\\someFolder\\someFile.html"
You could try it

c# savefilediaglog saving text of specific length

my code is-
Stream myStream;
saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Ticket files (*.tkt)|*.tkt";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.Title = "Save text Files";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
myStream = saveFileDialog1.OpenFile();
if (myStream != null)
{
StreamWriter wText = new StreamWriter(myStream);
string st = gettxt();
wText.Write(st);
//wText.WriteLine("sdfsderfsdsf");
myStream.Close();
}
}
whenever i uncomment Writeline and comment write(st) notthing is written..
and the string should be of specific length then only data is saved in the tkt file..
and last problem is that if text is too large then part of the text is only written..
please help me
try with
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
TextWriter tw = new StreamWriter(saveFileDialog1.FileName);
tw.WriteLine(gettxt());
tw.Close();
}
Hope this helps.
There are very few ways to explain the problem, other than there's a problem with the app that reads the file. Beware that you are writing a .txt file, it might not necessarily be compatible with a .tkt file format. Whatever that looks like. For one, the file will contain a BOM, 3 bytes at the start of the file that says it is a utf-8 formatted text file.
One thing you could try to diagnose the problem better:
using (var wText = new StreamWriter(myStream, Encoding.Default)) {
string st = gettxt();
wText.Write(st);
//wText.WriteLine("sdfsderfsdsf");
}
The Encoding argument specifies that the characters should be written in the default code page and without a BOM.
saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Ticket files (*.tkt)|*.tkt";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.Title = "Save text Files";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream myStream = saveFileDialog1.OpenFile())
{
using (StreamWriter wText = new StreamWriter(myStream))
{
wText.WriteLine(gettext());
}
}
}

Categories