I'm getting the 'cannot be found' error although the file does exist and the path is right. I have tried AudiosInfo.txt.txt and it does not work.
FileStream f = new FileStream("AudiosInfo.txt", FileMode.Open);
StreamReader s = new StreamReader(f);
string l=s.ReadLine();
MessageBox.Show(l);
When you are using,
FileStream f = new FileStream("AudiosInfo.txt", FileMode.Open);
you have to ensure that, AudiosInfo.txt file must be stored in your solution's \bin\Debug folder.
Otherwise you have to give the full path.
This is how you can find the full path: right click on the AudiosInfo.txt file, click on properties, click on the details tab and take a look at the folder path.
Might need to use to find the the path
string filePath = #"C:\MyDir\MySubDir\myfile.ext";
string directoryName;
int i = 0;
while (filePath != null)
{
directoryName = Path.GetDirectoryName(filePath);
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
filePath, directoryName);
filePath = directoryName;
if (i == 1)
{
filePath = directoryName + #"\"; // this will preserve the previous path
}
i++;
}
/*
Related
I have automated a test script in selenium and c# whereby I click on an icon and it downloads a pdf file. I do not know the name of this file, so what I need is confirmations its been downloaded, the file name and then it deletes the file?
I have done some research and found some code but it doesn't work. Here is the latest code I have found but all it tells me in "files" is the number of pdf files in my directory.
string fileName = ConfigurationManager.AppSettings["Don't know file name"];
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads");
DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
FileInfo[] files = downloadDir.GetFiles("*.pdf");
var file = files.Where(x => x.Name.Replace(" ", "") == fileName + ".pdf").FirstOrDefault();
fileName = file.FullName;
In case someone wants to know I have figured it out. So here is the code to confirm file has been downloaded and exists and then its deleted:
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads");
DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
FileInfo[] files = downloadDir.GetFiles("*.pdf");
var filename = files[0].FullName;
string getFileName = Path.GetFileName(filename);
if (File.Exists(filename))
{
Console.WriteLine("The file has been downloaded successfully");
Console.WriteLine("The filename is: " + getFileName);
}
File.Delete(filename);
Hope it helps someone.
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.
Currently i am taking in multiple .txt files from a directory i have specified (sourceDirectory). I am generating new .csv files with the same name as the .txt files - one .csv file for each .txt file.
However i want to generate these new files in another directory which i have specified (directoryPath). If i run my program once it creates these files in the initial directory, however if i run my program again it now generates the files in the destination directory.
The following is my code where i complete the above:
static void Main(string[] args)
{
string sourceDirectory = #"C:directoryWhereTXTFilesAre";
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
readFile(currentFile);
}
string directoryPath = #"C:\destinationForCSVFiles";
}
I then create the new .csv files name based on the original .txt file like this:
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
// build hash set of filenames for performance
var files = new HashSet<string> (Directory.GetFiles(folder));
for (var index = 0; index < maxAttempts; index++)
{
// first try with the original filename, else try incrementally adding an index
var name = (index == 0)
? fileName
: String.Format("{0} ({1}){2}", fileBase, index, ext);
// check if exists
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
// try to create the file
try
{
return new FileStream(CSVfileName, FileMode.CreateNew, FileAccess.Write);
}
catch (DirectoryNotFoundException) { throw; }
catch (DriveNotFoundException) { throw; }
catch (IOException)
{
}
}
I don't see why it's creating the .csv files initially in the same directory that the .txt files are in and then second time i run my code it creates them in the directoryPath.
Desired output: sourceDirectory left as it is with only .txt files and directoryPath to hold the .csv files.
The only other place i call CreateFileWithUniqueName is within my readFile method, the code is below:
using (var stream = CreateFileWithUniqueName(#"C:destinationFilePath", currentFile))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
It seems that you are passing the full filename of the source file. This confuses the Path.Combine inside the CreateFileWithUniqueFilename because you are falling in this subtle remarks found on the documentation of Path.Combine
paths should be an array of the parts of the path to combine. If the
one of the subsequent paths is an absolute path, then the combine
operation resets starting with that absolute path, discarding all
previous combined paths.
You can fix it easily with
using (var stream = CreateFileWithUniqueName(#"C:\destinationFilePath",
Path.GetFileName(currentFile)))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
Or better extract the filename without path inside the CreateFileWithUniqueName
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileName(fileName);
fileBase = Path.GetFileNameWithoutExtension(fileBase);
var ext = Path.GetExtension(fileBase);
also, you should build your CSVfileName using the cleaned filename
var name = (index == 0)
? String.Format("{0}{1}", fileBase, ext);
: String.Format("{0} ({1}){2}", fileBase, index, ext);
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
which i used earlier (FileuploadControl tool used)
inside button click method
if (FileUploadControl.HasFile)
{
filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
string lines;
string root = Server.MapPath("~/");
string Template = root + filename;
using (StreamReader reader = new StreamReader(Template))
{
while ((lines = reader.ReadLine()) != null)
list.Add(lines); // Add to list.
}
//file is now in list
//MORE IMPORTANT CODE
}
But now I am just using FolderDialog
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog();
if (result == DialogResult.OK) {
textBox8.Text = folderDialog.SelectedPath;
Environment.SpecialFolder root = folderDialog.RootFolder
//...
}
How can i read the file so that i can only use the FolderBrowserDialog to read an entire file and extract data?
I guess you are working in Windows Forms now if you are using FolderDialog.
You should use better OpenFileDialog if you want the user to check a FILE, not a Folder.
You can read the file using System.IO classes once you have the path.
If the file is text for example you can do:
string FinalPath = OpenFileDialog.FileName;
string Text= System.IO.File.ReadAllText(FinalPath);
you can also read the file into byte()
byte[] file = System.IO.File.ReadAllBytes(FinalPath);
I have some code where I'm attempting to create a temporary file to be used as a zip file.
string tempPath = Path.GetTempFileName();
string targetPath =
string.Concat(Path.GetTempPath(),"//",Path.GetFileNameWithoutExtension(tempPath),".zip");
File.Move(tempPath, targetPath);
However a new file is being created instead of moving (renaming) the temp file.
I'm definitely confused...
Kevin
I think this is what you're looking for:
FileInfo.MoveTo()
var newFiles = System.IO.Directory.GetFiles(updateLocation).Select(file => new FileInfo(file));
var workingDirectory = Environment.CurrentDirectory;
var existingFiles = System.IO.Directory.GetFiles(workingDirectory).Select(file => new FileInfo(file));
newFiles.ToList().ForEach(newFile =>
{
var matchedFile = existingFiles.ToList().Find(delegate(FileInfo file) { return file.Name == newFile.Name; });
if(matchedFile != null)
{
if(newFile.LastWriteTimeUtc != matchedFile.LastWriteTimeUtc)
{
if(!Directory.Exists(TEMP_DIRECTORY_NAME))
Directory.CreateDirectory(TEMP_DIRECTORY_NAME);
matchedFile.MoveTo(Path.Combine(TEMP_DIRECTORY_NAME, matchedFile.Name));
newFile.CopyTo(Path.Combine(workingDirectory, newFile.Name));
}
}
else
newFile.CopyTo(Path.Combine(workingDirectory, newFile.Name));
});'
That's expected behavior. If you want the old file deleted, you need to explicitly do that.
Your code works for me.
Path.GetTempFileName()
will create a new 0 byte temporary file in your machines %TEMP% directory. After the File.Move line is run the temp file is renamed with a .zip extension.
After this you can now use the file:
using (var writeStream = new FileStream(targetPath, FileMode.Open, FileAccess.ReadWrite))
{
// CODE HERE
}