Save to file open by openfiledialog (C# 2008) - file

What I am trying to do is most likely very simple but afters spending hours I still cant figure out how to do it correctly. I am able to open a text file using the openfiledialog but cannot figure out to save back to that same file. I would like to also be able to check and see if the file is in use before writing to it. Here is my code for the open and save buttons:
public void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//This if statement checks if the user has saved any changes to the list boxes
if (MessageBox.Show(
"Have you saved your work?\nOpening a new file will clear out all list boxes.",
"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
//Clears out the listboxes
this.itemListBox.Items.Clear();
this.priceListBox.Items.Clear();
this.qtyListBox.Items.Clear();
//This will open the file dialog windows to allow the user to chose a file
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Harv's Hardware";
fileDialog.InitialDirectory = Directory.GetCurrentDirectory();
//File Filter
fileDialog.Filter = "txt files (*.txt)|*.txt";
fileDialog.FilterIndex = 2;
fileDialog.RestoreDirectory = true;
//This if statement executes is the user hits OK
if (fileDialog.ShowDialog() == DialogResult.OK)
{
//StreamReader readFile = File.OpenText(fileDialog.FileName);
currentFile = new StreamWriter(OpenFileDialog.FileName);
String inputString = null;
while ((inputString = readFile.ReadLine()) != null)
{
this.itemListBox.Items.Add(inputString);
inputString = readFile.ReadLine();
this.priceListBox.Items.Add(inputString);
inputString = readFile.ReadLine();
this.qtyListBox.Items.Add(inputString);
}
}
}
}
and save button
//Closes and open files
//Creates a new saveDialog
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.ShowDialog();
//Listens to the user input
StreamWriter writeFile = File.CreateText(saveDialog.FileName);
int indexInteger = 0;
//Writes the actual File
while (indexInteger < priceListBox.Items.Count)
{
writeFile.WriteLine(itemListBox.Text);
writeFile.WriteLine(itemListBox.Text);
writeFile.WriteLine(qtyListBox.Text);
indexInteger++;
}
}
Thanks for any help!

Use SaveFileDialog instead of OpenFileDialog and can use FileStream to write to the file.
To check if file is in use or not, this is what I do..
public bool IsFileInUse(String file)
{
bool retVal = false;
try
{
using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
//file is not locked
}
}
catch
{
retVal = true;
}
return retVal;
}

Related

Saving and retrieving files in Codenameone

I have an app with data files (some images and xml files) i have packed them up in a zip file.
I open the file with zipme and save the files. I used this code for that
private void save1( ) {
InputStream is;
FileChooser.showOpenDialog(".zip", new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e != null && e.getSource() != null) {
String file = (String)e.getSource();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream is = fs.openInputStream(file);
ZipInputStream zipStream = new ZipInputStream(is);
ZipEntry entry;
// create a buffer to improve copy performance later.
byte[] buffer = new byte[2048];
while ((entry = zipStream.getNextEntry()) != null) {
String s = entry.getName();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
if (outdir.length() > 0) {
outdir = outdir ;
}
String outpath = outdir + "/" + entry.getName();
OutputStream output = null;
try {
output = FileSystemStorage.getInstance().openOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
} finally {
// we must always close the output file
if (output != null) {
output.close();
}
}
} } catch (IOException ex) {
Log.p(ex.getMessage(), 0); } } }});}
i see in netbeans that in the simulator the files are saved to
users/.cn1
So this works on the desktop
To fetch the image i use
String outdir = FileSystemStorage.getInstance().getAppHomePath();
Image uur1 = EncodedImage.create(outdir + "/West.jpg");
i also tried without outdir but also no luck.
What do i wrong.
This should work without the extra slash:
Image uur1 = EncodedImage.create(outdir + "West.jpg");.
Notice that this code is case sensitive so make sure the file has the right casing. Is this failing on the simulator, if so place a breakpoint on the loading code and make sure the file is physically there
The answer i found on my question is:
1 No extra slash as Shai Among suggested:
2 Make a inputstream for enecodedimage.create() instead of only a string with the path to the file
Without the second part the app doesn't run correctly in the simulation and on the device
FileSystemStorage fs = FileSystemStorage.getInstance();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
String outpath = outdir + West.jpg;
InputStream isk = fs.openInputStream(outpath);
Image uur = EncodedImage.create(isk);

using file upload ADF

Mine is adf 11.1.1.6 application
My requirement is to provide user a dialog, though which user would select the file in his local machine and upload the same in some destination folder.
I have an inputfile and button.
InputStream inputstream; //global variable in the bean
File file //global variable in the bean
on vcl of input file:
file = (UploadedFile)valueChangeEvent.getNewValue();
try {
inputstream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
on the click of button:
File destFile=new File("c:\\abc\\upload\\test.txt");
try {
if(!destFile.exists()){
destFile.createNewFile();
}
OutputStream output = new FileOutputStream("c:\\abc\\upload\\test.txt");
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputstream.read(buf)) > 0) { /// inputstream captured on vcl
output.write(buf, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
I noted that the test.txt was created of size 0kb but without any content it.
What is wrong here?

Groovy File.getText() - Do I have to close something?

If I use the File.getText() method in groovy
newFile().text or newFile().getText()
do I have to execute some closure statements to close the used file reader or will the method do it by itself?
It will do it by itself.
Calling new File( 'a.txt' ).text will call ResourceGroovyMethods.getText( File )
public static String getText(File file, String charset) throws IOException {
return IOGroovyMethods.getText(newReader(file, charset));
}
Which as you can see calls IOGroovyMethods.getText( BufferedReader ):
public static String getText(BufferedReader reader) throws IOException {
StringBuilder answer = new StringBuilder();
// reading the content of the file within a char buffer
// allow to keep the correct line endings
char[] charBuffer = new char[8192];
int nbCharRead /* = 0*/;
try {
while ((nbCharRead = reader.read(charBuffer)) != -1) {
// appends buffer
answer.append(charBuffer, 0, nbCharRead);
}
Reader temp = reader;
reader = null;
temp.close();
} finally {
closeWithWarning(reader);
}
return answer.toString();
}
Which as you can see, closes the Reader when done

"File system error (1003)" opening BlackBerry file connection

I tried the example from "J2ME/Blackberry - how to read/write text file?". I want only the read functionality, the file I want to read is in CSV format as a .txt file placed in the /res/test.txt.
But I am having an issue with the FileConnection. I get the following error:
File system error (1003)
Any suggestions or advice on a better approach or as to how I can get this working?
public class FileDemo extends MainScreen {
public FileDemo() {
setTitle("My Page");
String str = readTextFile("file:///test.txt");
System.out.println("Contents of the file::::::: " + str);
}
public String readTextFile(String fName) {
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.openInputStream(fName);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return result;
}
}
try this
InputStream is = getClass().getResourceAsStream("/test.txt");
StringBuffer buff = new StringBuffer();
int ch;
try {
while ((ch = is.read()) != -1)
buff.append((char) ch);
} catch (Exception e) {
Log.Error(e, "Exception ");
}
String str = (buff.toString());
Same problem I also faced in my project. First check your simulator memory card is inserted or not. From simulator,
go to Options(Settings)-->Device-->Storage and Check the Memory card Storage.
If the memory card is not inserted, than it will show Media Card is not currently inserted in the device. So, you need to insert the memory card. From simulator menu bar, choose simulate-->Change SD Card...
You can add the SD card here. Than you try.
I think, This suggestion will help someone.

Siverlight 4.0: How open a file

I want to create a program which opens my file onClick by providing its content in byte[] format in new page.
Please help.
The OpenFileDialog provides this capability, and it works the same in Silverlight versions from 2 through 4.
Here's a simple function that reads the bytes into a byte array for you.
http://msdn.microsoft.com/en-us/library/system.windows.controls.openfiledialog(VS.95).aspx
OpenFileDialog ofd = new OpenFileDialog()
{
Multiselect = false,
};
if (ofd.ShowDialog() == true)
{
FileInfo file = ofd.File;
byte[] bytes;
using (FileStream fs = file.OpenRead())
{
bytes = new byte[fs.Length];
int l = (int)fs.Length;
int r = 0;
while (l > 0)
{
int read = fs.Read(bytes, r, l);
if (read != 0)
{
r += read;
l -= read;
}
}
}
// All the bytes of the file are now in the "bytes" array
}

Resources