how to upload multiple files in c# windows application - winforms

I want to upload multiple files using single upload button. When I select more than one files it uploads and leaves rest of the files. Here is my code:
private void buttonBrowse_Click(object sender, EventArgs e)
{
try
{
var o = new OpenFileDialog();
o.Multiselect = true;
if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string FileName = o.FileName;
string filenames = Path.GetFileName(o.FileName);
FileName = FileName.Replace(filenames,"").ToString();
FTPUtility obj = new FTPUtility();
if (obj.UploadDocsToFTP(FileName, filenames))
{
MessageBox.Show("File Uploaded Successfully...", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadfiles();
}
}
else
{
MessageBox.Show("File Not Uploaded", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
this.LoadFiles();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Set MultiSelect property of OpenFileDialog to true and then use FileNames property to get all selected files.
o.FileNames.ToList().ForEach(file =>
{
//upoaad each file separately
});
FileNames
Gets the file names of all selected files in the dialog box.
For example your code may be like this:
var o = new OpenFileDialog();
o.Multiselect = true;
if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var ftp = new FTPUtility();
var failedToUploads= new List<string>();
var uploads= new List<string>();
o.FileNames.ToList().ForEach(file =>
{
var upload= ftp.UploadDocsToFTP(file, Path.GetFileName(file)));
if(upload)
uploads.Add(file);
else
failedToUploads.Add(file);
});
var message= string.Format("Files Uploaded: \n {0}", string.Join("\n", uploads.ToArray()));
if(failedToUploads.Count>0)
message += string.Format("\nFailed to Upload: \n {0}", string.Join("\n", failedToUploads.ToArray()));
MessageBox.Show(message);
this.LoadFiles();
}
This way you can show a message that informs the user about his uploaded files or which one of them that is failed to upload.

Related

c# - How to put each zip file from source folder to target folder using 7z function

I have a window form, which contains two buttons to let a user choose the input directory and output directory like below. In addition, I have a fileSystemWatcher to monitor the empty source folder and timer to use with the zip function. The user can select a directory (which contain some sub-folder) and click start to create a zip file, and they can put that zip file to any directories from their preference.
the result will be like this
However, I failed to create the zip file to the selected directory using 7zip, neither the naming matches the subdirectory from the source folder. Below is my code to process the zip function using 7zip.
string source = textBoxInput.Text + "\\*";
string[] files = Directory.GetFiles(textBoxInput.Text, "*.7z", SearchOption.AllDirectories);
string target = tBoxOutput.Text + "\\everySingleZipFile"; // the target location only contains zip file from the source location
foreach (var file in files)
{
// process zip for every file, no idea how to implement it.
_sevenZip.CreateZipFile(source, target);
}
Here is my 7z method
public void CreateZipFile(string sourceName, string targetName)
{
ProcessStartInfo zipProcess = new ProcessStartInfo();
zipProcess.FileName = #"E:\Program Files\7-Zip\7z.exe"; // select the 7zip program to start
zipProcess.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
zipProcess.WindowStyle = ProcessWindowStyle.Minimized;
Process zip = Process.Start(zipProcess);
zip.WaitForExit();
}
This is the button for the user to choose which directory to put the zip file.
private void btnOutput_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = $"Choose an output path";
if (fbd.ShowDialog() == DialogResult.OK)
{
// show the path in the text box
tBoxOutput.Text = fbd.SelectedPath;
}
}
EDIT:
the main problem you have is choosing a directory as an output instead of a file.
I made a screen similar to yours
after choosing directories for output and input
the code for the browse button events:
private void btnBrowseInput_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
txtInput.Text = fbd.SelectedPath;
}
}
}
private void btnBrowseOutput_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtInput.Text))
{
MessageBox.Show("Please choose an input folder first");
return;
}
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
var directoryName = Path.GetFileName(txtInput.Text);
txtOutput.Text = Path.Combine(fbd.SelectedPath, directoryName + ".7z");
}
}
}
and the code for the zip button event:
string zipProgramPath = #"C:\Program Files\7-Zip\7z.exe";
public Form1()
{
InitializeComponent();
}
private void btnZip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtInput.Text) || string.IsNullOrEmpty(txtOutput.Text))
{
MessageBox.Show("Choose input directory and output file");
}
else
{
CreateZipFile(txtInput.Text, txtOutput.Text);
}
}
public void CreateZipFile(string sourceName, string targetName)
{
try
{
ProcessStartInfo zipProcess = new ProcessStartInfo();
zipProcess.FileName = zipProgramPath; // select the 7zip program to start
zipProcess.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
zipProcess.WindowStyle = ProcessWindowStyle.Minimized;
zipProcess.UseShellExecute = true;
Process zip = Process.Start(zipProcess);
zip.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

display bytes from database as image in imageview in javafx

please I have been stuck on how to convert my stored images from my
database and display it as an image in imageview in javafx.
All the
previously asked questions have not helped me.
I'm using objectdb as my database
I also used fxml to build my GUI
for (Person p : person) {
name.setText(p.getName());
gender.setText(p.getGender());
byte[] byteArray = p.getImage();
image.setImage(new Image(new ByteArrayInputStream(byteArray)));
}
I'll show a detailed step on saving to the database using a file chooser and writing an image to a file in a directory(folder) on your hard drive, and also displaying it to imageview in fmxl GUI.
The following below are triggered during a button event or initialized
from the controller
FileChooser choose = new FileChooser();
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
choose.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
File file = choose.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
byte[] b;
try (ByteArrayOutputStream out = new ByteArrayOutputStream(262144)) {
ImageIO.write(bufferedImage, "jpg", out);
out.flush();
b = out.toByteArray();
}
EntityService service = new EntityService();
Person p = new Person();
p.setId(UUID.randomUUID().toString());
p.setImage(b);
service.putPerson(p);
} catch (IOException e) {
e.printStackTrace();
}
Person p = service.getPerson();
byte[] byteArray = p.getImage();
ByteArrayInputStream in = new ByteArrayInputStream(byteArray);
BufferedImage read = ImageIO.read(in);
image.setImage(SwingFXUtils.toFXImage(read, null));
String output = "C:\\java\\images\\1.jpg";
try (FileOutputStream fos = new FileOutputStream(output)) {
fos.write(byteArray);
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex);
} catch (IOException ioe) {
System.out.println("IOException : " + ioe);
}

FileSystemStorage isDirectory returns false for a directory

I am trying to write a file browser in CN1 to let the user select a profile picture for upload.
I tried using the FileSystemStorage's isDirectory() method, but it is returning false for a directory.
Code:
private void displayFiles(final Container c, String root)
{
c.removeAll();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
String files[] = fs.listFiles(root);
for(final String file: files)
{
System.out.println(file+"-->"+fs.isDirectory(file));
if(fs.isDirectory(file))
{
Button b = new Button("Folder::"+file);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
displayFiles(c, file);
}
});
c.addComponent(b);
}else
{
Container c1 = new Container(new BoxLayout(BoxLayout.X_AXIS));
Label l = new Label("File::"+file);
CheckBox cb = new CheckBox();
c1.addComponent(l);
c1.addComponent(cb);
c.addComponent(c1);
}
}
} catch (IOException ex) {
}
c.revalidate();
}
Output:
CN1Log__$-->false
CN1Preferences-->false
Cookies-->false
data-->false
FaceBookAccesstmp652635968-->false
folder1-->false
folder2-->false
HELLOCN1FS-->false
myFileName-->false
token-->false
Screenshot of the emulator:
Screenshot of the explorer
The behavior is same on the phone as well
Could this be a bug ?
Is there something that I am not doing correctly ?
Thanks
You need to use the full path for the file:
if(fs.isDirectory(root + file))

Reading file to imageView

I'm tryin to pick a file and read it into an imageView. I'm using java fx.
Here's my code:
public void changeImage() {
try {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose Image");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(ScreenController.stage);
if (selectedFile != null) {
File file = selectedFile;
File desc = new File("/" + file.getName());
FileUtils.copyFile(file, desc);
Image img = new Image(desc.getPath());
profileImage.setImage(img);
}
} catch (Exception e) {
System.err.println(e);
}
}
The problem seems to be Image img = new Image (desc.getPath()); getting an error that the file does not exist. But it does and it is a image.
// Alex
The Image constructor needs a String representation of a URL, not a filesystem path.
Replace
Image img = new Image(desc.getPath());
with
Image img = new Image(desc.toURI().toURL().toExternalForm());

How can I save and open a file in winForms?

I have this application where I use windowsForm and UserControl to draw some diagrams. After I am done I want to save them or I want to open an existing file that I created before and keep working on the diagram. So, I want to use the save and open dialog File to save or open my diagrams.
EDIT:
this is what i have :
//save the object to the file
public bool ObjectToFile(Object model, string FileName)
{
try
{
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_BinaryFormatter.Serialize(_MemoryStream, model);
byte[] _ByteArray = _MemoryStream.ToArray();
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray.ToArray(), 0, _ByteArray.Length);
_FileStream.Close();
_MemoryStream.Close();
_MemoryStream.Dispose();
_MemoryStream = null;
_ByteArray = null;
return true;
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return false;
}
//load the object from the file
public Object FileToObject(string FileName)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
long _TotalBytes = new System.IO.FileInfo(FileName).Length;
byte[] _ByteArray = _BinaryReader.ReadBytes((Int32)_TotalBytes);
_FileStream.Close();
_FileStream.Dispose();
_FileStream = null;
_BinaryReader.Close();
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_MemoryStream.Position = 0;
return _BinaryFormatter.Deserialize(_MemoryStream);
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return null;
}
and now I want to do this but it's not working
public void save()
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.OpenFile() != null)
{
ObjectToFile(model, saveFileDialog1.FileName);
}
}
}
but if I try without the fileDialog and i just use
ObjectToFile(model, "d:\\objects.txt");
this works. And I want to save it where I want and with my own name.
Check out the SaveFileDialog and OpenFileDialog classes. They are pretty similar, and can be used like this:
using(SaveFileDialog sfd = new SaveFileDialog()) {
sfd.Filter = "Text Files|*.txt|All Files|*.*";
if(sfd.ShowDialog() != DialogResult.OK) {
return;
}
ObjectToFile(sfd.FileName);
}
The mechanics of actually saving your file are, obviously, outside the scope of this answer.
Edit: I've updated my answer to reflect the new information in your post.

Resources