How save uploaded file? c# mvc - c#

I want upload an image file to project's folder but I have an error in my catch:
Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
My code is:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
Thank you :)

Try this:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);

Your error is the following:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
File.Exists(....);

You need filename
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));

Remove the last part of the path to save you have an extra "/"
It should be
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.

Related

replace file with new one with timestamp

I have a file in a directory:
Path.Combine(dir1, "participants.txt")
I want to check if participants.txt exists in dir1. And if it does copy it to a new file named participants[timestamp].txt. And replace the old one with the information lines.
I have tried this:
if (File.Exists(Path.Combine(dir1, "participants.txt")))
{
File.Copy("participants.txt", "participants" + Stopwatch.GetTimestamp().ToString() + ".txt");
File.WriteAllLines("participants.txt", lines);
}
But this isn't working. Any ideas?
You are missing the full path in your filename specifiers:
String source = Path.Combine(dir1, "participants.txt");
if (File.Exists(source)) {
File.Copy(source, Path.Combine(dir1, "participants" + Stopwatch.GetTimestamp().ToString() + ".txt"));
File.WriteAllLines(source, lines);
}

File uploading into server

I am making a website having image upload module.In my localhost server its working perfectly. That means i can upload images and save it. But when i host my solution i am getting a error. That is, Access to the path is denied.
This is the code i have used...
string fileName = FileUpload1.FileName.ToString();
string uploadFolderPath = "~/up_foto/";
string filePath = HttpContext.Current.Server.MapPath(uploadFolderPath);
FileUpload1.SaveAs(filePath + "\\" + fileName);`
What the wrong in this.. Please help me....
Thanks in advance....
I am afraid there's nothing wrong with your code, if it runs locally. Instead, you have to make sure if on the host environment the user "IUSER", or "IIS_IUSER", or the like, has access (Read/Write) to the upload folder.
Since you are getting "Access to the path is denied", Did you check the folder you are trying to upload is having write access
you can use Path.combine or server.mappath (dont forget to add System.IO in the namespaces)
string fileName = FileUpload1.FileName.ToString();
string uploadFolderPath = "~/Uploads/Images/";
string filePath1 = Server.MapPath(uploadFolderPath + fileName);
or
string fileName = FileUpload1.FileName.ToString();
string uploadFolderPath = "~/Uploads/Images/";
string filePath = Server.MapPath(uploadFolderPath);
string filePath1= Path.Combine(filepath1 + fileName);

C# - Saving a '.txt' File to the Project Root

I have written some code which requires me to save a text file. However, I need to get it to save to my project root so anyone can access it, not just me.
Here's the method in question:
private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
string fileName = Microsoft.VisualBasic.Interaction.InputBox("Please enter a save file name.", "Save Game");
if (fileName.Equals(""))
{
MessageBox.Show("Please enter a valid save file name.");
}
else
{
fileName = String.Concat(fileName, ".gls");
MessageBox.Show("Saving to " + fileName);
System.IO.File.WriteAllText(saveScene.ToString(), AppDomain.CurrentDomain.BaseDirectory + #"\" + fileName);
}
}
catch (Exception f)
{
System.Diagnostics.Debug.Write(f);
}
}
Many people told me that using AppDomain.CurrentDomain.BaseDirectory would contain the dynamic location of where the app was stored. However, when I execute this, nothing happens and no file is created.
Is there another way of doing this, or am I just using it completely wrong?
File.WriteAllText requires two parameters:
The first one is the FileName and the second is the content to write
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + #"\" + fileName,
saveScene.ToString());
Keep in mind however that writing to the current folder could be problematic if the user running your application has no write permission for the folder. (And in latest OS writing to the Program Files is very limited). If it is possible, change this location to the ones defined in Environment.SpecialFolder enum
I wish also to suggest using the System.IO.Path class when you need to build paths and not a string concatenation where you use the very 'OS specific' constant "\" to separate paths.
In your example I would write
string destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,fileName);
File.WriteAllText(destPath, saveScene.ToString());
no need for the extra + #"\" just do:
AppDomain.CurrentDomain.BaseDirectory + fileName
and replace the parameters
saveScene.ToString()
and
AppDomain.CurrentDomain.BaseDirectory + fileName
your code should be:
private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
string fileName = Microsoft.VisualBasic.Interaction.InputBox("Please enter a save file name.", "Save Game");
if (fileName.Equals(""))
{
MessageBox.Show("Please enter a valid save file name.");
}
else
{
fileName = String.Concat(fileName, ".gls");
MessageBox.Show("Saving to " + fileName);
System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + fileName, saveScene.ToString());
}
}
catch (Exception f)
{
System.Diagnostics.Debug.Write(f);
}
}
you can read on File.WriteAllText here:
Parameters
path Type: System.String
The file to write to.
contents Type: System.String
The string to write to the file.
Instead of using AppDomain.CurrentDomain.BaseDirectory you can just do it this way:
File.WriteLine("data\\Mytxt.txt", "Success!");
When you don't add anything, the basedirectory is automatically assumed.

Image saving into database from a folder and get back into the UI

I have a field in my app (c#) to save an image into the database. I written the following code to save the image into a folder and then save the path into the database. But the image is not getting saved into the folder.
string imgName = FileUpload1.FileName.ToString();
string imgPath = null;
if (imgName == "")
{
//int taxiid = Convert.ToInt32(HiddenField1.Value);
Taxi t = null;
t = Taxi.Owner_GetByID(tx.Taxi_Id, USM.OrgId);
imgPath = t.CarImage;
}
else
{
imgPath = "ImageStorage/" + imgName;
}
FileUpload1.SaveAs(Server.MapPath(imgPath));
tx.CarImage = imgPath;
I think your problem is that you add the name to the Path I try it and for me it works fine if I save it like this:
FileUpload1.SaveAs(Server.MapPath("ImageStorage") + imgName);
And as #Rahul mentioned add a try catch to prevent errors.
And you check
if (imgName == "")
According to my understanding it's not posible that imgName is "" but anyway you better add a check if the fileupload has a file.
if (FileUploadControl.HasFile)

How to copy a file to another path?

I need to copy a file to another path, leaving the original where it is.
I also want to be able to rename the file.
Will FileInfo's CopyTo method work?
Have a look at File.Copy()
Using File.Copy you can specify the new file name as part of the destination string.
So something like
File.Copy(#"c:\test.txt", #"c:\test\foo.txt");
See also How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo, here's a sample:
FileInfo fi = new FileInfo(#"c:\yourfile.ext");
fi.CopyTo(#"d:\anotherfile.ext", true); // existing file will be overwritten
I tried to copy an xml file from one location to another. Here is my code:
public void SaveStockInfoToAnotherFile()
{
string sourcePath = #"C:\inetpub\wwwroot";
string destinationPath = #"G:\ProjectBO\ForFutureAnalysis";
string sourceFileName = "startingStock.xml";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.
You could also use File.Copy to copy and File.Move to rename it afterwords.
// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);
// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
// However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
// File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
// throw new IOException("Failed to rename file after copying, because destination file exists!");
EDIT
Commented out the "rename" code, because File.Copy can already copy and rename in one step, as astander noted correctly in the comments.
However, the rename code could be adapted if the OP desired to rename the source file after it has been copied to a new location.
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.
This is what I did to move a test file from the downloads to the desktop.
I hope its useful.
private void button1_Click(object sender, EventArgs e)//Copy files to the desktop
{
string sourcePath = #"C:\Users\UsreName\Downloads";
string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] shortcuts = {
"FileCopyTest.txt"};
try
{
listbox1.Items.Add("Starting: Copy shortcuts to dektop.");
for (int i = 0; i < shortcuts.Length; i++)
{
if (shortcuts[i]!= null)
{
File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);
listbox1.Items.Add(shortcuts[i] + " was moved to desktop!");
}
else
{
listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!");
}
}
}
catch (Exception ex)
{
listbox1.Items.Add("Unable to Copy file. Error : " + ex);
}
}
TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code
MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
if (Fromtb.Text=="")
{
MessageBox.Show("Ples You Should Write All Text Box");
Fromtb.Select();
return;
}
else if (Nametb.Text == "")
{
MessageBox.Show("Ples You Should Write The Third Text Box");
Nametb.Select();
return;
}
else if (Totb.Text == "")
{
MessageBox.Show("Ples You Should Write The Second Text Box");
Totb.Select();
return;
}
string fileName = Nametb.Text;
string sourcePath = #"" + Fromtb.Text;
string targetPath = #"" + Totb.Text;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
//when The User Write The New Folder It Will Create
MessageBox.Show("The File is Create in "+" "+Totb.Text);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
MessageBox.Show("The File is copy To " + Totb.Text);
}
Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code
class Program
{
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = #"E:\C-sharp-IO\test.txt";
//duplicate file path
string PathForDuplicateFile = #"E:\C-sharp-IO\testDuplicate.txt";
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile);
Console.ReadKey();
}
}
Source: File I/O in C# (Read, Write, Delete, Copy file using C#)
File.Move(#"c:\filename", #"c:\filenamet\filename.txt");

Categories

Resources