Usare savefiledialog

mercoledì 19 aprile 2006 - 17.20

kiara83 Profilo | Junior Member

come faccio a salvare un documento tramite savefiledialog, dandogli il nome che voglio?

alx_81 Profilo | Guru

ciao!
che tipo di documento devi salvare?
Alx81 =)

kiara83 Profilo | Junior Member

devo salvare un file .html risultato di una trasformazione xsl applicata a xml
Non so come si fa a salvare effettivamente il mio file dandogli il nome che desidero

alx_81 Profilo | Guru

riesci a postare il codice?

Alx81 =)

kiara83 Profilo | Junior Member

ti posto un pezzo di codice:
private void Btrasforma_Click(object sender, System.EventArgs e)
{
FileImmagine selectxslt = (FileImmagine)LBxslt.SelectedItem;
XslTransform trasformazione = new XslTransform();
trasformazione.Load(selectxslt.Path);
FileImmagine selectxml = (FileImmagine)LBxml.SelectedItem;
XmlUrlResolver resolver = new XmlUrlResolver ();
XPathDocument doc = new XPathDocument(selectxml.Path);
XmlReader reader = trasformazione.Transform(doc, null, esolver);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(reader);
}

qui ti ho messo il codice del pulsante trasforma che ha il compito di effettuare la trasformazione.
Quello che vorrei sapere è come faccio a salvare il mio xmldoc cliccando sul pulsante salva che mi apre la savefiledialog?
Come faccio a scegliere un nome che voglio e a sapere che mi sta salvando il mio file xml?

Brainkiller Profilo | Guru

>Quello che vorrei sapere è come faccio a salvare il mio xmldoc
>cliccando sul pulsante salva che mi apre la savefiledialog?
>Come faccio a scegliere un nome che voglio e a sapere che mi
>sta salvando il mio file xml?

E' molto semplice, l'oggetto SaveDialog espone delle proprietà tra cui Filename che contiene il nome file selezionato dall'utente, ti riporto un pezzo di codice tratto dal Framework SDK. Adattalo in base alle tue necessità:

// Displays a SaveFileDialog so the user can save the Image // assigned to Button2. 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(); }

ciao


David De Giacomi
Microsoft MVP
http://blogs.dotnethell.it/david/

alx_81 Profilo | Guru

eccoti qui =)

//FileImmagine selectxslt = (FileImmagine)LBxslt.SelectedItem;
//XslTransform trasformazione = new XslTransform();
//trasformazione.Load(selectxslt.Path);
//FileImmagine selectxml = (FileImmagine)LBxml.SelectedItem;
XmlUrlResolver resolver = new XmlUrlResolver ();
//XPathDocument doc = new XPathDocument(selectxml.Path);

//XmlReader reader = new XmlReader ;
//trasformazione.Transform(doc, null, esolver);
XmlDocument xmldoc = new XmlDocument();
// usa il tuo reader da qui
xmldoc.Load("c:\\prova.xml");
saveFileDialog1.Filter = "(*.xml) Xml Files|*.xml";
saveFileDialog1.DefaultExt = "xml";
saveFileDialog1.InitialDirectory = "c:\\"; //metti la directory che ti serve
saveFileDialog1.ShowDialog();
xmldoc.Save(saveFileDialog1.FileName);
Alx81 =)

kiara83 Profilo | Junior Member

grazie, una cosa sola:
mettendo il codice così la finestra per salvare mi si apre quando clicco su trasforma e non su salva, come vorrei.
Come posso modificarlo allora?
In teoria dovrei incollarle nel metodo bottonsalva_click, ma non so come fare a richiamare da lì il mio xmldoc

alx_81 Profilo | Guru

Quando premi trasforma salvi il tuo reader in una variabile di scope globale (della form) e poi nel salva metti solo le mie aggiunte, passando la variabile di scope globale..
Alx81 =)

kiara83 Profilo | Junior Member

scusa ma non ho ben capito il funzionamento del reader;
qual è la variabile di scope globale?

XmlReader reader = trasformazione.Transform(doc, null, esolver);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(reader);

questo è il codice che ho sotto il click_trasforma;
non riesco a capire come posso richiamare il mio documento dal click_salva.
dovrò creare un nuovo doc xml e con load caricarci il documento che ho memorizzato con il reader.

alx_81 Profilo | Guru

mi sono espresso male, il tuo documento deve essere di scope globale..
nel tuo caso xmldoc.. basta che sposti la dichiarazione dal metodo alla definizione dei campi della classe..
ad esempio

class miaclasse
{
XmlDocument xmldoc;

private void btnSalva_Click(object sender, System.EventArgs e)
{
saveFileDialog1.Filter = "(*.xml) Xml Files|*.xml";
saveFileDialog1.DefaultExt = "xml";
saveFileDialog1.InitialDirectory = "c:\\"; //metti la directory che ti serve
saveFileDialog1.ShowDialog();
xmldoc.Save(saveFileDialog1.FileName);
}
}

fammi sapere..
Alx81 =)

kiara83 Profilo | Junior Member

Mi viene questo errore dopo che è partito tutto:
An unhandled exception of type 'System.NullReferenceException' occurred in TrasfXML.exe

Additional information: Riferimento a un oggetto non impostato su un'istanza di oggetto.

alx_81 Profilo | Guru

Prima, ovviamente devi lanciare il trasforma.. e solo dopo clickare salva..
questo è sottointeso, vero?
Alx81 =)

kiara83 Profilo | Junior Member

si, l'ho fatto ma non funge.
se io metto la dichiarazione docxml fuori dal tutto senza inizializzarlo non commetto un errore?

alx_81 Profilo | Guru

nel trasform devi istanziarlo e caricarlo, nel save devi solo salvarlo..
io ho provato il codice di seguito con un file xml qualunque.. e funziona..

private void button1_Click(object sender, EventArgs e)
{
//FileImmagine selectxslt = (FileImmagine)LBxslt.SelectedItem;
//XslTransform trasformazione = new XslTransform();
//trasformazione.Load(selectxslt.Path);
//FileImmagine selectxml = (FileImmagine)LBxml.SelectedItem;
//XmlUrlResolver resolver = new XmlUrlResolver ();
//XPathDocument doc = new XPathDocument(selectxml.Path);

//XmlReader reader = new XmlReader ;
//trasformazione.Transform(doc, null, esolver);
xmldoc = new XmlDocument();
xmldoc.Load("c:\\prova.xml");
}

private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "(*.xml) Xml Files|*.xml";
saveFileDialog1.DefaultExt = "xml";
saveFileDialog1.InitialDirectory = "c:\\"; //metti la directory che ti serve
saveFileDialog1.ShowDialog();
xmldoc.Save(saveFileDialog1.FileName);
}
Alx81 =)

kiara83 Profilo | Junior Member

ma il "c:\\prova.xml" da dove l'hai preso?
Quindi tu l'xmldoc l'hai dichiarato sotto la classe senza inizializzarlo?

alx_81 Profilo | Guru

Per me il c:\prova.xml è un file ad hoc, creato da me..
tu hai il reader.. non ti serve il file xml.. era il mio esempio..

Quello che io ho dichiarato a livello di classe è un semplice campo tipizzato..
Non lo istanzio, ne dichiaro solo il tipo.. non sei obbligata ad utilizzare la new.. per capirci.. =)
Alx81 =)

kiara83 Profilo | Junior Member

mi viene questo errore e non capisco perchè visto che è identico al tuo il mio codice:

Additional information: Riferimento a un oggetto non impostato su un'istanza di oggetto.

Io ho messo:
XmlDocument xmldoc;
sotto public class Form1
è giusto e perchè mi fa quel cavolo di errore??

alx_81 Profilo | Guru

così non posso aiutarti..
mi serve sapere su che riga ti dà errore..
oppure postami il codice per bene che gli do un'occhiata..
Alx81 =)

kiara83 Profilo | Junior Member

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;

namespace TrasfXML
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox LBxml;
private System.Windows.Forms.Button Bxml;
private System.Windows.Forms.Button Bxslt;
private System.Windows.Forms.ListBox LBxslt;
private System.Windows.Forms.FolderBrowserDialog FBDxml;
private System.Windows.Forms.FolderBrowserDialog FBDxslt;
private System.Windows.Forms.Button Btrasforma;
private System.Windows.Forms.ListBox LBtrasforma;
private System.Windows.Forms.Button Bsalva;
private System.Windows.Forms.SaveFileDialog SFDtrasforma;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.Splitter splitter2;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
XmlDocument xmldoc;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();


//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.LBxml = new System.Windows.Forms.ListBox();
this.Bsalva = new System.Windows.Forms.Button();
this.FBDxml = new System.Windows.Forms.FolderBrowserDialog();
this.LBtrasforma = new System.Windows.Forms.ListBox();
this.LBxslt = new System.Windows.Forms.ListBox();
this.Btrasforma = new System.Windows.Forms.Button();
this.Bxslt = new System.Windows.Forms.Button();
this.Bxml = new System.Windows.Forms.Button();
this.FBDxslt = new System.Windows.Forms.FolderBrowserDialog();
this.SFDtrasforma = new System.Windows.Forms.SaveFileDialog();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.splitter1 = new System.Windows.Forms.Splitter();
this.splitter2 = new System.Windows.Forms.Splitter();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.panel4.SuspendLayout();
this.SuspendLayout();
//
// LBxml
//
this.LBxml.Dock = System.Windows.Forms.DockStyle.Fill;
this.LBxml.Location = new System.Drawing.Point(0, 40);
this.LBxml.Name = "LBxml";
this.LBxml.Size = new System.Drawing.Size(104, 238);
this.LBxml.TabIndex = 11;
//
// Bsalva
//
this.Bsalva.Location = new System.Drawing.Point(216, 8);
this.Bsalva.Name = "Bsalva";
this.Bsalva.Size = new System.Drawing.Size(80, 24);
this.Bsalva.TabIndex = 10;
this.Bsalva.Text = "Salva";
this.Bsalva.Click += new System.EventHandler(this.Bsalva_Click_1);
//
// LBtrasforma
//
this.LBtrasforma.Dock = System.Windows.Forms.DockStyle.Fill;
this.LBtrasforma.Location = new System.Drawing.Point(0, 0);
this.LBtrasforma.Name = "LBtrasforma";
this.LBtrasforma.Size = new System.Drawing.Size(368, 277);
this.LBtrasforma.TabIndex = 13;
//
// LBxslt
//
this.LBxslt.Dock = System.Windows.Forms.DockStyle.Fill;
this.LBxslt.Location = new System.Drawing.Point(0, 40);
this.LBxslt.Name = "LBxslt";
this.LBxslt.Size = new System.Drawing.Size(104, 238);
this.LBxslt.TabIndex = 12;
//
// Btrasforma
//
this.Btrasforma.Location = new System.Drawing.Point(64, 8);
this.Btrasforma.Name = "Btrasforma";
this.Btrasforma.Size = new System.Drawing.Size(80, 24);
this.Btrasforma.TabIndex = 9;
this.Btrasforma.Text = "Trasforma";
this.Btrasforma.Click += new System.EventHandler(this.Btrasforma_Click);
//
// Bxslt
//
this.Bxslt.Dock = System.Windows.Forms.DockStyle.Top;
this.Bxslt.Location = new System.Drawing.Point(0, 0);
this.Bxslt.Name = "Bxslt";
this.Bxslt.Size = new System.Drawing.Size(104, 40);
this.Bxslt.TabIndex = 8;
this.Bxslt.Text = "Scegli Directory";
this.Bxslt.Click += new System.EventHandler(this.Bxslt_Click);
//
// Bxml
//
this.Bxml.Dock = System.Windows.Forms.DockStyle.Top;
this.Bxml.Location = new System.Drawing.Point(0, 0);
this.Bxml.Name = "Bxml";
this.Bxml.Size = new System.Drawing.Size(104, 40);
this.Bxml.TabIndex = 7;
this.Bxml.Text = "Scegli Directory";
this.Bxml.Click += new System.EventHandler(this.Bxml_Click);
//
// panel1
//
this.panel1.Controls.Add(this.LBxml);
this.panel1.Controls.Add(this.Bxml);
this.panel1.Dock = System.Windows.Forms.DockStyle.Left;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(104, 286);
this.panel1.TabIndex = 14;
//
// panel2
//
this.panel2.Controls.Add(this.LBxslt);
this.panel2.Controls.Add(this.Bxslt);
this.panel2.Dock = System.Windows.Forms.DockStyle.Left;
this.panel2.Location = new System.Drawing.Point(104, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(104, 286);
this.panel2.TabIndex = 15;
//
// panel3
//
this.panel3.Controls.Add(this.panel4);
this.panel3.Controls.Add(this.LBtrasforma);
this.panel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel3.Location = new System.Drawing.Point(208, 0);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(368, 286);
this.panel3.TabIndex = 16;
//
// panel4
//
this.panel4.Controls.Add(this.Btrasforma);
this.panel4.Controls.Add(this.Bsalva);
this.panel4.Dock = System.Windows.Forms.DockStyle.Top;
this.panel4.Location = new System.Drawing.Point(0, 0);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(368, 40);
this.panel4.TabIndex = 14;
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(208, 0);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(8, 286);
this.splitter1.TabIndex = 17;
this.splitter1.TabStop = false;
//
// splitter2
//
this.splitter2.Location = new System.Drawing.Point(216, 0);
this.splitter2.Name = "splitter2";
this.splitter2.Size = new System.Drawing.Size(3, 286);
this.splitter2.TabIndex = 18;
this.splitter2.TabStop = false;
//
// saveFileDialog1
//
this.saveFileDialog1.Title = "Salva con Nome";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(576, 286);
this.Controls.Add(this.splitter2);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Bxml_Click(object sender, System.EventArgs e)
{
DialogResult dr = FBDxml.ShowDialog();

if ( dr == DialogResult.OK)
{
string a = FBDxml.SelectedPath;
string [] files = Directory.GetFiles(a,"*.XML");
foreach (string f in files)
{
string nome = Path.GetFileNameWithoutExtension(f);
FileImmagine aobj = new FileImmagine(f,nome);
LBxml.Items.Add(aobj);
}

}
}

private void Bxslt_Click(object sender, System.EventArgs e)
{
DialogResult dr = FBDxslt.ShowDialog();

if ( dr == DialogResult.OK)
{
string a = FBDxslt.SelectedPath;
string [] files = Directory.GetFiles(a,"*.XSL");
foreach (string f in files)
{
string nome = Path.GetFileNameWithoutExtension(f);
FileImmagine bobj = new FileImmagine(f,nome);
LBxslt.Items.Add(bobj);
}
}
}

private void Btrasforma_Click(object sender, System.EventArgs e)
{
FileImmagine selectxslt = (FileImmagine)LBxslt.SelectedItem;
XslTransform trasformazione = new XslTransform();
trasformazione.Load(selectxslt.Path);
FileImmagine selectxml = (FileImmagine)LBxml.SelectedItem;
XmlUrlResolver resolver = new XmlUrlResolver ();
XPathDocument doc = new XPathDocument(selectxml.Path);
XmlReader reader = trasformazione.Transform(doc, null, resolver);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(reader);
}

private void Bsalva_Click_1(object sender, System.EventArgs e)
{
SFDtrasforma.Filter = "(*.xml) Xml Files|*.xml";
SFDtrasforma.DefaultExt = "xml";
SFDtrasforma.InitialDirectory = "C:\\";
SFDtrasforma.ShowDialog();
xmldoc.Save(SFDtrasforma.FileName);
}
}
}

Se ne hai voglia..questo è il codice

alx_81 Profilo | Guru

mi mancano FileImmagine ed altre cose, come la form e i controlli..
prova a dirmi la riga su cui si ti ritorna errore.. perchè il metodo continua a funzionare.. =)

o sennò temo che mi serva il progetto ;-)
almeno la form coi suoi eventi..

kiara83 Profilo | Junior Member

ti ho allegato tutto, guarda se ne hai voglia; secondo me non funziona perchè xmldoc se lo dichiaro fuori senza inizializzarlo vale zero e quindi quando lo richiamo nel botton_click di salva me lo considera uguale a zero. Non c'è un altro modo per richiamare quel file xml che ho caricato in xmldoc??

alx_81 Profilo | Guru

Corretto..
c'è un errore nel tuo codice.

Nel metodo..

private void Btrasforma_Click(object sender, System.EventArgs e)
{
FileImmagine selectxslt = (FileImmagine)LBxslt.SelectedItem;
XslTransform trasformazione = new XslTransform();
trasformazione.Load(selectxslt.Path);
FileImmagine selectxml = (FileImmagine)LBxml.SelectedItem;
XmlUrlResolver resolver = new XmlUrlResolver();
XPathDocument doc = new XPathDocument(selectxml.Path);
XmlReader reader = trasformazione.Transform(doc, null, resolver);
// ERRORE!!!
XmlDocument xmldoc = new XmlDocument();
// ---------------------------------------------------------------
xmldoc.Load(reader);
}

Fai l'errore di ridichiarare la variabile xmldoc. In questo modo crei una nuova variabile di visibilità (scope) del metodo e quindi, anche se ha lo stesso nome, non utilizzi quella corretta (di scope globale della classe).
Basta sostituire la riga indicata con "xmldoc = new XmlDocument();". In questo modo utilizzi quella già dichiarata esternamente, e funziona..
ok?
fammi sapere!
ciao!
Alx81 =)

kiara83 Profilo | Junior Member

grazie tante.
Ti dovrei fare un regalo, x tutto il tempo che hai perso per sto cavolo di programma; sai sono pochi giorni che sto dietro a c# e winforms...e quindi non sono molto esperta

alx_81 Profilo | Guru

nemmeno io.. sono giovane(25, ormai verso i 30 =))), pensa li compio domani) e devo imparare un sacco!!! =)
cmq.. niente regalo.. mi basta la risposta accettata ;-) (è quasi un tuo regalo di compleanno)

e non ho perso molto..
trovo divertente rispondere (con quel poco che conosco) al forum..

Il fatto è che avrei anche un sacco di domande..
ma non sempre ho tempo di postarle..

ok.. buon proseguimento..
a risentirci!! =)
Alx81 =)

Brainkiller Profilo | Guru

>nemmeno io.. sono giovane(25, ormai verso i 30 =))), pensa li
>compio domani) e devo imparare un sacco!!! =)

Auguri coscritto ! anche io 25 già compiuti però.

Ciao

David De Giacomi
Microsoft MVP
http://blogs.dotnethell.it/david/

alx_81 Profilo | Guru

Cavolo.. a 25 anni MVP..
ti invidio =)
poi, hai già 5 stellette.. ci sto lavorando =)
purtroppo è da poco che posto.. non ci sono mai riuscito (motivi vari.. lasciamo perdere)..

Come hai fatto a diventare MVP??
mi piacerebbe un sacco!
Alx81 =)
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?

Dopo esserti registrato potrai chiedere
aiuto sul nostro Forum oppure aiutare gli altri

Consulta le Stanze disponibili.

Registrati ora !
Copyright © dotNetHell.it 2002-2024
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5