I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));
Related
I'm trying to create an album and what I want to do, is to copy a picture from its original path to a specific folder and rename (the copy) right after.
Here is a piece of my code (note that "picturedir" is a path):
string PCname = Environment.UserName;
Image File;
OpenFileDialog openfile = new OpenFileDialog();
openfile.InitialDirectory = #"C:\Users\" + PCname + #"\Pictures";
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
pictureBox3.Image.Save(picturedir + "\\" + openfile.SafeFileName);
System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName,
picturedir + "\\" + "1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As seen in the last line inside the "try", I want to rename the chosen picture, simply to "1". However, this last line gives an error "Cannot create a file when that file already exists". Any ideas?
P.S.: If I do not use the last "try" line: System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1"); it does copy the chosen picture but it obviously does not rename it at all.
Here is an article about work with files.
From article:
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
}
If you use different file names, you get copy with new name.
I am trying to connect to a remote server and access a specific directory in that server for searching a file but for some reason it shows that the directory doesnt exist on the server even though it actually exists. I am guessing that my file path is wrong. Can anyone please suggest me if I made a syntax error?
filepath = #"\\172.17.20.11\E$\MessageLogs\" + logType + "\\" + country + "\\" + year + "\\" + month + "\\" + day + "\\";
private void GetFiles(string filePath)
{
try
{
tblFileContent = new DataTable();
getColumns(tblFileContent);
//C:\MessageLogs\ElmaCore\KENYA\2016\March\22
//filePath = #"C:\MessageLogs\"+filePath; //Pick a folder on your machine to store the uploaded files
if (!Directory.Exists(filePath))
{
fn.MessageLine(this.Page, "Log folder does not exist.", System.Drawing.Color.Red, "lblMessageLine");
dtDate.Focus();
return;
}
string searchReference = txtReference.Text.Trim();
//string filePath = System.Configuration.ConfigurationManager.AppSettings["InFolder"].ToString();
DirectoryInfo DirInfo = new DirectoryInfo(filePath);
FileInfo[] CsvFiles = DirInfo.GetFiles("*" + searchReference + "*.log").OrderByDescending(p => p.LastWriteTime).ToArray();
if (CsvFiles.Length > 0)
{
foreach (var file in CsvFiles)
{
string FileName = file.Name;
string sourceFile = System.IO.Path.Combine(filePath, FileName);
ProcessFile(FileName, sourceFile);
}
//LoadGrid();
}
else {
fn.MessageLine(this.Page, "Sorry, No files found for the specified reference.", System.Drawing.Color.Red, "lblMessageLine");
txtReference.Focus();
return;
}
}
catch (Exception ex)
{
fn.MessageLine(this.Page, "Sorry an Error Occured. Please try again", System.Drawing.Color.Red, "lblMessageLine");
ErrLogger.LogError("filelog-" + ex.Message); //oledbconn.Close();
return;
}
}
As you say your directory exists than it might the problem with permission.
Please make sure account under which code is been running have permission to that folder.
Also note that once you deploy in IIS, change identity of apppool to a domain user who has permission.
If you want to verify if its permission problem, than just do this.
Right click into that folder and give permission to everyone and test.
I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?
here is y code to upload:
protected void btnAddExpenditure_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
//check file Extension & Size
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
you're still using the original FileUpload1.PostedFile.FileName. This should be changed to
string ReceiptFileName = Path.GetFileName(FileName);
EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then
FileName = Guid.NewGuid() + FileName;
would result in something like 123-4321-GUIDC:\Folder\File.txt
I doubt that's what you want. You might want to flip that around
FileName = FileName + Guid.NewGuid();
I am trying to upload a file using File Upload. Then compare this file with a repository using IEnumerable. I want the IEnumerable list to save the path of the uploaded file. I am trying to do so, but it's giving me an error :
Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\Uploaded file.txt'
The code is as follows:
//File upload method uploads the file
protected string File_Upload()
{
string strFilename;
strFilename = File1.PostedFile.FileName;
strFilename = System.IO.Path.GetFileName(strFilename);
File1.PostedFile.SaveAs(#"E:\" + strFilename); /*saves the uploaded file in the specified directory */
return strFilename; /*returns the file name and it's path*/
}
protected void Button2_Click(object sender, EventArgs e)
{
String StrFileNmae =File_Upload(); /* Receives the file name and path*/
string file1 = StrFileNmae;
IEnumerable<string> list1 = File.ReadLines(file1);
IEnumerable<string> list2 = Directory.EnumerateFiles(#"E:\DocxDB", "*.txt", SearchOption.AllDirectories);
IList<string> difference = list2.Except(list1).ToList();
if (difference != null)
{
lbl_Result.Text = "Files do not match.";
}
}
Try this, the File_Upload method returns the file name but not the path it's in. Without a path the server will try and load it from the current directory.
protected string File_Upload()
{
string strFilename;
strFilename = File1.PostedFile.FileName;
strFilename = System.IO.Path.GetFileName(strFilename);
File1.PostedFile.SaveAs(#"E:\" + strFilename); /*saves the uploaded file in the specified directory */
return #"E:\" + strFilename; // <--- Change is here
}
I try to upload image to folder (using FileUpload) by pressing one submit button to whole form. i manage to upload the image to separate folders but i can't display it.
thank you.
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(".") + "\\images\\" + ulProj.groupCode;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
Directory.CreateDirectory(path);
fname = path + "\\" + tempFU.FileName;
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;
}
catch
{
//return;
}
Points to remember:
you should use tilde ~ operator to represent the current project
root folder.
use System.IO.Path.Combine() to combine your path and filename to get the valid complete path.
you are creating the Directory for the given path 2 times. so remove the later part where you are creating the Directory 2'nd time.
as said in the above comments as your catch block is not having anycode,
remove the try-catch block
Complete Solution:
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(#"~\images\" + ulProj.groupCode);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
fname = System.IO.Path.Combine(path,tempFU.FileName);
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;