Can not upload file from C# (WPF) FTP - c#

i have created a small ftp program in c# using winforms but when i try to create this in wpf it is showing me an error "Value cannot be null. Parameter name:fileName", The code works fine in winform.
here is the code:
public partial class Ftp : UserControl
{
string filePath;
public Ftp()
{
InitializeComponent();
}
//Clear TextBox when clicked
#region textBox clear
public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
//TextBox tb = (TextBox)sender;
//tb.Text = string.Empty;
//tb.GotFocus -= TextBox_GotFocus;
}
#endregion
//Open File Dialog
private void browser_click(object sender, RoutedEventArgs e)
{
#region File Dialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.CheckFileExists = true;
dlg.DefaultExt = ".txt";
dlg.Filter = "JPEG Files (*.txt)|*.txt|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
dlg.FileName = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Open document
string filename = dlg.FileName;
pathtext.Text = filename;
}
#endregion
}
//Upload the File to FTP
private void Upload_click(object sender, RoutedEventArgs e)
{
#region Upload files
if (filePath == "")
{
MessageBox.Show("Please Select The File To Upload..");
}
else
{
browser.IsEnabled = false;
try
{
FileInfo fileInfo = new FileInfo(filePath);
string fileName = fileInfo.Name.ToString();
WebRequest requestFTP = WebRequest.Create("ftp://" + hosttext.Text + "/" + fileName);
requestFTP.Credentials = new NetworkCredential(usertext.Text, passtext.Password);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fStream = fileInfo.OpenRead();
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = requestFTP.GetRequestStream();
int contentLength = fStream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
MessageBox.Show("File Uploading Is SuccessFull...");
}
catch (Exception ep)
{
MessageBox.Show("ERROR: " + ep.Message.ToString());
}
browser.IsEnabled = true;
filePath = "";
hosttext.Text = usertext.Text = passtext.Password = pathtext.Text = "";
}
#endregion
}
}

You never set your filePath variable, so it's null. In browser_click you need to do something like
if (result == true)
{
// Open document
string filename = dlg.FileName;
filePath = filename; //added this line
pathtext.Text = filename;
}
Also, you think you have handled your invalid string here:
if (filePath == "")
but at that point filePath = null.
Instead, use if (string.IsEmptyOrNull(filePath))

Related

Issue with method CopyTo

I'm working on my first WPF application, and I'm trying to copy the browsed image into designated folder, however I have problem with CopyTo function.
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Select image(*.JPG;*.PNG)|*.JPG;*.PNG";
openFileDialog1.Title = "Select your image";
openFileDialog1.InitialDirectory = #"C:\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// The image to be shown into PictureBox
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
// The Image
var theImg = Image.FromFile(openFileDialog1.FileName);
string fileName = openFileDialog1.FileName;
if(theImg != null)
{
string exePath = System.Environment.GetCommandLineArgs()[0];
string destinationFolder = Path.Combine(exePath, "Profiles");
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
}
string filePath = Path.Combine(destinationFolder, fileName);
using(var fileStream = new FileStream(filePath, FileMode.Create))
{
theImg.CopyTo(theImg, fileStream);
}
}
}
}
Error: No overload for method 'CopyTo' takes 2 arguments
How can I solve this issue? Thank you in advance

How to check if text file is already added or opened

I would like to open and add a text file content into a list Box, but if I want to add another text file, how do I check if the file that I add is already added into the list Box. I mean I don't want the list box to be duplicated.
private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Text file|*.txt";
openFileDialog.Title = "Open Text";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(openFileDialog.OpenFile()))
{
string line;
while ((line = r.ReadLine()) != null)
{
donutListBox.Items.Add(line);
}
}
}
}
Add an if:
if ( !donutListBox.Items.Contains(line) ){
donutListBox.Items.Add(line);
}
If you on .net framework 4+, you can use File.ReadAllLines(string filename) static method:
private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Text file|*.txt";
openFileDialog.Title = "Open Text";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var lines = File.ReadAllLines(openFileDialog.FileName);
lines = lines.Where(line => !donutListBox.Items.Contains(line)).ToArray();
donutListBox.Items.AddRange(lines);
}
}
You can try is
public static bool IsFileInUse(string filename)
{
bool locked = false;
try
{
FileStream fs =
File.Open(filename, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
fs.Close();
}
catch (IOException ex)
{
locked = true;
}
return locked;
}
And :
if(!Class.IsFileInUse("FilePAth") && !donutListBox.Items.Contains(line))
{
//your code
}

How to save filename only to the gridview but I need path while downloading the file

I got finally, how to download the file using the path. But I was wondering how can I keep the file name only on the grid view. While I need the full path for downloading.
On debugging I came to see that I cannot keep file name only on file upload. Since it is carried to the downloading section. If I keep file name, then file name is carried to the downloading part and the file is not downloaded.
Can anyone help me
Codes
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
Your question is not clear. But if i get you right. Why don't you use use a column for the name and a hidden/0 width column for the file path. Its a grid and therefore you may have many columns. Plus i am thinking the code below should return the full path , unless you trim and can't see where you trim .
string strfilename = fileDialog.FileName;
To get the file name only you can use the Path
string filenameOnly= System.IO.Path.GetFileName(strfilename);
The above should return your file name only you can check here for better understanding.
Add another column and set the width to 0 . Example below
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 0;
cncInfoDataGridView.Columns.Add(column);
Save your file path in the new column width a 0 width and retrieve during download.
A similar question was asked here.
How to extract file name from file path name?
Dictionary<int, byte[]> _myAttachments;
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1)
{
UploadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnDownload_Click(object sender, EventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] binaryData = File.ReadAllBytes(fileDialog.FileName);
dataGridView1.Rows[dgvCell.RowIndex].Cells[1].Value = fileInfo.Name;
if (_myAttachments.ContainsKey(dgvCell.RowIndex))
_myAttachments[dgvCell.RowIndex] = binaryData;
else
_myAttachments.Add(dgvCell.RowIndex, binaryData);
}
}
}
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = null;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
byteData = _myAttachments[dgvCell.RowIndex];
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
}
}
}

There is an error in XML document (0, 0) during deserialization

i have the following code to for xml serialization.
public class FormSaving
{
private string major;
public string Majorversion
{
get;
set;
}
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = #"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
FormSaving abc = new FormSaving();
abc.Majorversion = MajorversionresultLabel.Content.ToString();
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, abc);
}
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
Stream checkStream = null;
Microsoft.Win32.OpenFileDialog DialogLoad = new Microsoft.Win32.OpenFileDialog();
DialogLoad.Multiselect = false;
DialogLoad.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
if ((bool)DialogLoad.ShowDialog())
{
try
{
if ((checkStream = DialogLoad.OpenFile()) != null)
{
loadpath = DialogLoad.FileName;
checkStream.Close();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
{
System.Windows.MessageBox.Show("Problem occured, try again later");
}
FormSaving abc;
using (Stream loadstream = new FileStream(loadpath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
abc = (FormSaving)serializer.Deserialize(loadstream);
}
MajorversionresultLabel.Content = abc.Majorversion;
}
When i press the SaveButton, my label.content is saved into an xml file. However when i press the load button to load this xml file, i get the error "There is an error in XML document (0, 0)". I went to open my xml file after pressing the load button, it becomes blank and everything got erased. Can anyone help me fix this load button error?
ok solved,
using (Stream loadstream = new FileStream(loadpath, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
abc = (FormSaving)serializer.Deserialize(loadstream);
}
should have been FileMode.Open instead of FileMode.Create

Deleting file in asp.net using c#?

When I save a document file in my solution explorer, I send that doc file through mail then I am wanting to delete the document file. It is giving an error like this: process being
used by another process.
Below please find my code:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if (Label1.Text == txtverifytxt.Text)
{
if (rdoSevice.SelectedItem.Value == "1")
{
PackageType = ddlindPackages.SelectedItem.Text;
}
else if (rdoSevice.SelectedItem.Value == "2")
{
PackageType = ddlCorpPack.SelectedItem.Text;
}
if (ResumeUpload.PostedFile != null)
{
HttpPostedFile ulFile = ResumeUpload.PostedFile;
string file = ulFile.FileName.ToString();
FileInfo fi = new FileInfo(file);
string ext = fi.Extension.ToUpper();
if (ext == ".DOC" || ext == ".DOCX")
{
int nFileLen = ulFile.ContentLength;
if (nFileLen > 0)
{
strFileName = Path.GetFileName(ResumeUpload.PostedFile.FileName);
strFileName = Page.MapPath("") + "\\Attachments\\" + strFileName;
ResumeUpload.PostedFile.SaveAs(strFileName);
}
sendingmail();
FileInfo fi1 = new FileInfo(strFileName);
ResumeUpload.FileContent.Dispose();
Label2.Visible = true;
Label2.Text = "Request sent sucessfully";
fi1.Delete();
//if (File.Exists(strFileName))
//{
// File.Delete(strFileName);
//}
ClearAll(tblOrdernow);
//Response.Redirect("CheckOut.aspx");
}
else
{
Label2.Visible = true;
Label2.Text = "Upload only word documents..";
}
}
else
{
Label2.Visible = true;
Label2.Text = "Do not upload empty document..";
}
}
else
{
Label2.Visible = true;
Label2.Text = "Verify Image not Matched";
Label1.Text = ran();
}
}
The most likely cause is the stream you created from
ResumeUpload.PostedFile.SaveAs
hasn't been closed. You could try to force it by disposing or closing the stream. HttpPostedFile has an InputStream property you can use for this:
InputStream
Gets a Stream object that
points to an uploaded file to prepare
for reading the contents of the file.

Categories