I am currently dealing with an issue in iPads were when you upload an image via my site the image is renamed to "image.jpg" which is an issue as if it's in the same directory it can cause issues.. so I am trying to stop it renaming the file OR to add an incremental number onto the end of it, however I can't get this to function correctly.
I have used this small snippet of code to try and fix it, however it doesn't seem to work.
if(File.Exists(filename))
{
fileName = String.Format("{0}({1}", fileName, count++);
inputFile.PostedFile.SaveAs( String.Format( "{0}\\{1}", directory, fileName ) );
}
else
{
inputFile.PostedFile.SaveAs( String.Format( "{0}\\{1}", directory, fileName ) );
}
}
File.Exists(filename) expects complete file path to see if the file exists or not.
but in the line inputFile.PostedFile.SaveAs, you are concatenating filepath to be
directory + "//" + fileName.
so does your fileName actually consists of fullpath, or just the actual filename with extension?
if fileName consists of fullPath, inputFile.PostedFile.SaveAs should not work, as it would point to invalid location, and if fileName consists of just the file name and not complete path, then, File.Exists should not work. either way your logic is flawed.
I guess, now you know, what to change.
also, instead of using a counter, simply append DateTime.Now.ToString("hhmmddttmmss") to the fileName to make it unique.
When you call:
if(File.Exists(filename))
Make sure that filename includes the full path on disk to where you save the files.
From the looks of it you may want to use Path.Combine(directory, fileName) rather than just filename on its own.
You can generate the filename as
filename = filename + DateTime.Now.Ticks.ToString();
so that it will always be the new file. I mean it will retain the old as well as new file.
I hope it will help you.. :)
try this
fileName= Path.Combine(directory,fileName );
if(File.Exists(filename))
{
fileName = fileName + DateTime.Now.Ticks;
}
inputFile.PostedFile.SaveAs( fileName );
Related
I am trying to use the ZipArchiveMode to zip up a few files. The files are in different directories.
zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression);
I'm calling this for each file.
Is there a way to keep the folder integrity within the file so that it unzips in to the correct folder?
If not, do I have any other options for compressing files?
Thank you
Instead of just Path.GetFileName(file), use whatever portion of the fullname of the file is appropriate for your application. Something like this might work:
FileInfo fi = new FileInfo(file);
string path = fi.Directory.Parent + "\\" + fi.Name;
I'm trying to move a file from the desktop to a directory called "Textfiles" but every time I try to it gives me this error.
Additional information: The target file "C:\Users\Developer\Documents\Textfiles" is a directory, not a file.
Now I know that using
File.Copy(fileName, targetPath);
Would be wrong and that's what I am using right now, It takes two parameters, the first being the file yopu want to copy and the second one being the file it's replacing? Correct me if i am wrong on the second parameter.
Anyways, I tried System.IO.Directory.Move(fileName, destFile); aswell but that pretty much gave me the same error.
The two parameters are very simple, just two string that consists of paths.
string fileName = filePath.ToString();
string targetPath = #"C:\Users\Developer\Documents\Textfiles";
What would be the correct way to transfer fileName to targetPath ?
You need to specify the destination filename.
string fileOnly = System.IO.Path.GetFileName(fileName);
string targetPath = System.IO.Path.Combine(#"C:\Users\Developer\Documents\Textfiles", fileOnly);
System.IO.File.Move(fileName, targetPath);
See https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
for documentation:
destFileName
Type: System.String
The name of the destination file. This cannot be a directory or an existing file.
You have to add the new file name to the destination directory.
You can get the file name with:
result = Path.GetFileName(fileName);
thus in your case:
string targetPath = #"C:\Users\Developer\Documents\Textfiles\" + Path.GetFileName(fileName);
I need to add a file name/file extension at the end of GetCurrentDirectory. I want to make the .txt file and write text to it
StreamWriter sw = new StreamWriter(Directory.GetCurrentDirectory, );
sw.WriteLine(a + ":Qwerty124");
sw.Close();
Is what i have so far. I want to make the file of the current directory + \example.txt
if the current directory is Sys32 it would look like this
C:\Windows\System32\example.txt
You can use the System.IO.Path.Combine method to append the file name at the end of the path. It essentially does a string append behind the scenes but it is smart enough to use the proper path separator and add it if necessary.
System.IO.Path.Combine(Directory.GetCurrentDirectory(), "example.txt");
Path.Combine
https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx
Path.Combine(Directory.GetCurrentDirectory(), "example.txt")
Hello I would like to know if it was possible to extract the files from the ressources folder to copy thme in a directory at the moment i've tried this :
protected void Form1_Load(object sender, EventArgs e)
{
FileInfo info = new FileInfo(file);
info.CopyTo(PATH + "\\shell" + "\\" + file, true);
Bitmap bmp = (Bitmap)Properties.Resources.ResourceManager.GetObject(file);
Image bitmap = Bitmap.FromFile(Environment.GetFolderPath (Environment.SpecialFolder.Desktop) + "ConnectableCORR\\ApplicationConnectTable\\Resources\\teapot.jpg");
bitmap.Save(Path.GetDirectoryName(PATH + "\\shell" + "\\" + "thumbnail_3D.png"), System.Drawing.Imaging.ImageFormat.Png);
}
But the copy isn't working am I doing anything wrong?
Best regards.
The method "Save" of object "Image" requires the name of file in "filename", and you are sending it:
Path.GetDirectoryName(PATH + "\\ shell" + "\\" + "thumbnail_3D.png")
Path.GetDirectoryName
Would return:
PATH + "\\ shell" + "\\"
Would fail the file name, you should also include the file name.
Edit
Try this and check the paths:
FileInfo info = new FileInfo(file);
MessageBox.Show(string.Format("File '{0}' exist '{1}'", info.FullName, info.Exists));
var destinationFile = string.Format("{0}\\shell\\{1}", PATH, file);
info.CopyTo(destinationFile, true);
MessageBox.Show(string.Format("File '{0}' exist '{1}'", destinationFile, File.Exists(destinationFile)));
I'm going to focus on the info.CopyTo() call, as that is the better way of your two options to copy the file. As it is written, there are a number of possibilities as to why it isn't working. For everything I'm thinking about, an exception would be thrown, so you should be able to add a try-catch block around your code and debug to see what the error is. Here's my best guesses, in the order I would try to debug them:
What is file? Is it a filename? Is it a full path plus filename? It looks to me like your code expects it to be fully-qualified in one place and just the name in another.
Source file doesn't exist. I would do a quick info.Exists to confirm that the file exists before trying to copy it.
Make sure the output filename makes sense. If file includes a path, then you really probably want to do info.CopyTo(PATH + "\\shell\\" + info.Name, true) unless you want to include the source path in the output path.
Output directory doesn't exist. If this is the case. A DirectoryNotFoundException will be thrown. Check if the directory exists and create it before doing your CopyTo.
Bad file name. Might contain invalid characters, which will cause either an ArgumentException or a NotSupportedException.
Path too long. Probably not this, but a PathTooLongException would be thrown.
I have got this read file code from microsoft
#"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks
You can skip the path - this will read file from the working directory of the program.
Just #"task_2.txt" will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then #ken2k's solution will be much more robust.
If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT:
More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);
If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.
You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = Path.Combine(myDocuments, #"mikec\assignment2\task_2.txt");
// TODO: do something with the file like reading it for example
string contents = File.ReadAllText(file);
Use the relative path.
you can put your file inside the folder where your application resides.
you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use
Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();