i have this code snippet
private List<string> FolderOne(string Folder)
{
string filena;
DirectoryInfo dir = new DirectoryInfo(Folder);
FileInfo[] files = dir.GetFiles("*.mp3", SearchOption.AllDirectories);
List<string> str = new List<string>();
foreach (FileInfo file in files)
{
str.Add(file.FullName);
filena = file.FullName;
filena.Replace("*.mp3", "*.jpg");
if (filena.Length > 0)
{
pictureBox1.Image = new System.Drawing.Bitmap(filena.ToString()); //I receive a error "Parameter is not valid."
}
}
return str;
}
My purpose was to make read the picture box the file.fullname ".mp3" in the same folder but end with ".jpg",infact i have 2 file in a folder the first one is a song "firstsong.mp3" and the second one a picture "firstsong.jpg" the difference between them is the final extension so i try to make read to picturebox the same filename but with extension ".*jpg" and i receive an error "Parameter is not valid." in the line code "pictureBox1.Image = new System.Drawing.Bitmap(filena.ToString());".
How i can work out that?
Thanks for your attention
Nice Regards
There are some other issues with your code. First off, you are storing all the mp3 file names, but only displaying the last image loaded.
As far as replacing the extension, use Path's method to do that:
string musicFile = "mysong.mp3";
string imageFile = Path.ChangeExtension(musicFile, "jpg");
Switch to:
filena = filena.Replace(".mp3", ".jpg");
if (filena.Length > 0)
{
pictureBox1.Image = new System.Drawing.Bitmap(filena);
}
The main problem is with filena.Replace("*.mp3", "*.jpg");
There are two issues in that line.
First, you're searching on "*.mp3" instead of just ".mp3". The individual filenames do not have the * character, and string.Replace doesn't use regular expressions, just string matching.
Second, strings in .NET are immutable. They cannot be changed once they're created. This means that you can't replace the value of a string in place - you always return a new string. So string.Replace(...) will return a new string.
I'd add to the previous suggestions by adding that you should check that the jpg exists by doing the following:
if (File.Exists(jpgFilePath)) {
pictureBox1.Image = new System.Drawing.Bitmap(jpgFilePath);
}
Related
So basically i am making an app that will sync file types is different ways, I want to search the whole of a logical Drive for example C:\ for all text files.How ever once i find all the text files i want to apply an action for example move all text files to one location or email all text files to the users email.
I have found this code from a past Stack overflow post
public List<string> Search()
{
var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
{
try
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
}
catch(Exception e)
{
Logger.Log(e.Message); // Log it and move on
}
}
return files;
}
But what i want to know is how do i do somthing when i find the files ?
The code you posted looks like it should fill List<string> files with strings representing names of files that have a .txt extension.
It should be as simple as iterating over the value returned from the function and doing as you please with them.
This code should (untested) check for a target directory, create it if it doesn't exist, and then copy each file returned from Search() to the target path.
List<string> results = Search();
String targetPath = "C:/TargetDirectory/";
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
foreach (string aFileStr in results)
{
String sourceFile = aFileStr;
String destFile = Path.Combine(targetPath, Path.GetFileName(aFileStr));
System.IO.File.Copy(sourceFile, destFile, true);
}
You would do a foreach on the list of strings that that function returns.
I'm not quite sure if I understand you correctly. If you just want to know how to process your filelist, you could for instance do the following:
var filelist = Search();
foreach (var s in filelist) {
string fn = System.IO.Path.GetFileName(s);
string dest = System.IO.Path.Combine("c:\\tmp", fn);
System.IO.File.Copy(s, dest, true);
}
which will copy all files in filelist to c:\tmp and overwrite files with equal filename.
This question already has an answer here:
Modify the content of specific line in text file
(1 answer)
Closed 8 years ago.
I'm having a textfile say something like this:
#TITLE:What's Up
#ARTIST:4 Non Blondes - Whats Up
#MP3:Four Non Blondes - Whats Up.mp3
#COVER:4 Non Blondes - Whats Up [CO].jpg
#BACKGROUND:4 Non Blondes - Whats Up [CO].jpg
#BPM:135
#GAP:32100
it's saved as 4 Non Blondes - Whats Up.txt
In the same folder there's a MP3 file which is in this example: 4 Non Blondes - Whats Up.mp3
What i want is to replace the line:
#MP3:Four Non Blondes - Whats Up.mp3
into this line:
#MP3:4 Non Blondes - Whats Up.mp3
Every MP3 line has infront of the line this:
#MP3:[Songname].mp3
I know i can do this manually but i have like 2k files like this, and they all need to link to the correct mp3 file. I'm trying this in C#, but without luck.
This is what i've tried so far:
private static void testMethod(string path)
{
var x = System.IO.Directory.GetDirectories(path);
foreach (var directory in x)
{
string[] mp3Files = System.IO.Directory.GetFiles(directory, "*.mp3");
string[] txtFiles = System.IO.Directory.GetFiles(directory, "*.txt");
string MP3FileNameWithExtensions = System.IO.Path.GetFileName(mp3Files[0]);
Console.WriteLine(txtFiles[0]);
var lines = System.IO.File.ReadAllLines(txtFiles[0]);
for (int i = 0; i < lines.Length; i++)
{
if(lines[i].Contains("#MP3")){
Console.WriteLine("Jeeeej working");
lines[i] = "#MP3:"+MP3FileNameWithExtensions;
System.IO.File.WriteAllLines(txtFiles[0], lines);
}
}
}
}
As the filename of the .txt file is [Songname].txt, you can use Path.GetFilenameWithoutExtension(files[i]) to get [Songname]. Then replace the #MP3 line with the filename + ".mp3". Now write out the file.
N.B. You will probably want to make a copy of the directory you are working on just in case something goes wrong.
I know I am late to the party but here is an example.
public void FixTheFiles(String startFolderPath)
{
foreach (String dirName in Directory.GetDirectories(startFolderPath))
{
FixTheFiles(dirName);
}
foreach (String fileName in Directory.GetFiles(startFolderPath))
{
FileInfo fi = new FileInfo(fileName);
if (fi.Extension.Equals("MP3"))
{
String fileContents = "";
using (StreamReader sr = new StreamReader(File.Open(fileName.Replace(".mp3",".txt"),FileMode.Open)))
{
String currentLine = sr.ReadLine();
if (currentLine.StartsWith("#MP3:"))
{
currentLine = "#MP3:" + fileName.Substring(fileName.LastIndexOf('\\')+1);
}
fileContents += currentLine;
}
using (StreamWriter sw = new StreamWriter(File.Open(fileName.Replace(".mp3",".txt"),FileMode.Open)))
{
sw.Write(fileContents);
}
}
}
}
I would simutaneously open a stream reader and a stream writer (with a different file name) and go through each file one line at a time searching for whatever changes you need to make. You can select your file names with an openfiledialog with Multiselect = true or run this command in a command prompt window to generate a textfile to paste in your code with quotation marks around them as initial values for a string array instantiation.
dir *.mp3 /b > filenames.txt
string[] array = new string[] {"file0.mp3",
"file1.mp3",
"file2.mp3",
"file3.mp3",
"file4.mp3",
"file5.mp3"};
How can I load all Images into an image list from a specific folder in c#? thanks!
List<Texture2D> images = new List<Texture2D>();
string folderPath = "MyImages/";
for(int i= 0; i<Count; i++) {
try{
images.Add(Content.Load<Texture2D>(folderPath + i.ToString));}
catch{break;}
}
This works but I need to convert the filenames into 1 to N. But I have to keep the filenames(the name of the personImage) for future use (for recognition output).
If you mean the image paths, you could try like this:
public List<String> GetAllImages(String directory)
{
return Directory.GetFiles(directory, "*.jpg", SearchOption.AllDirectories).ToList();
}
You can use foreach, in this case: (Don't forget to add using System.IO)
Here, set the folder to the DirectoryInfo
DirectoryInfo directory = new DirectoryInfo(#"C:\");
To get the right files you have to specify the type, i'm using jpg but can be png, bmp etc.
FileInfo[] Archives = directory.GetFiles("*.jpg");
Now, for each archive in the folder it will add to imagelist
foreach (FileInfo fileinfo in Archives)
{
imageList.Images.Add(Image.FromFile(fileinfo.FullName));
}
I've tested, worked. Alright?
I wrote a code to read all the files in a folder, then write them to a file. All the code complies and runs okay, but the filenames of the files are not displayed in the new file.
Code:
private void Form1_Load(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog(); // Show the dialog.
// create a list to insert the data into
//put all the files in the root directory into array
string[] array1 = Directory.GetFiles(#"C:\Users\a3708906\Documents\Filereader m 15062012", "*.csv");
// Display all files.
TextWriter tw1 = new StreamWriter("C:/Users/a3708906/Documents/Filereader m 15062012/Filereader m 15062012/listoffiles.txt");
List<string> filenames = new List<string>();
tw1.WriteLine("--- Files: ---");
foreach (string name in array1)
{
tw1.WriteLine(name);
}
tw1.Close();
}
I would be grateful for your assistance.
You took the trouble to ask the user the folder location, yet you don't retrieve that folder location. The code should be
string[] array1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.csv");
// Display all files.
TextWriter tw1 = new StreamWriter(folderBrowserDialog1.SelectedPath+"/listoffiles.txt");
If the file isn't created (ie its just not there, even if it's just blank) then you problem lies with the stream writer. If this is the case I would suggest changing the direction of slashes so that your path is
TextWriter tw1 = new StreamWriter("C:\\Users\\a370890\\Documents\\Filereader m 15062012\\Filereader m 15062012\\listoffiles.txt");
If the file is created but nothing is written have a look at the flush command.
tw1.Flush();
Set a breakpoint to verify that GetFiles is returning files.
(Consider renaming array1 to something more meaningful)
Set a breakpoint on tw1.WriteLine(name) and ensure it is being hit.
It should be pretty easy to see the problem. My guess is that you simply aren't getting any files returned from GetFiles, but the breakpoints will tell you for sure. If your output file is created but missing the files - this is most likely the case.
If your output file doesn't exist; take a closer look at your file writing code.
I would say that your "space" in your folderpath is messing things up. Try to escape the "whitespace" by following the explanations in the msdn
I think problem is with your file path or file writing capability.
You use folderbrowserdialog but do not use it to get selected file
name. Instead you give path manually. also your output path can have
problem.
Try this :
using(system.IO.StreamWriter tw1 =
new system.IO.StreamWriter(#"C:/Users/a3708906/Documents/Filereader m 15062012/Filereader m 15062012/listoffiles.txt")
{
foreach (string name in array1)
{
tw1.WriteLine(name);
}
}
Trying to extract files to a given folder ignoring the path in the zipfile but there doesn't seem to be a way.
This seems a fairly basic requirement given all the other good stuff implemented in there.
What am i missing ?
code is -
using (Ionic.Zip.ZipFile zf = Ionic.Zip.ZipFile.Read(zipPath))
{
zf.ExtractAll(appPath);
}
While you can't specify it for a specific call to Extract() or ExtractAll(), the ZipFile class has a FlattenFoldersOnExtract field. When set to true, it flattens all the extracted files into one folder:
var flattenFoldersOnExtract = zip.FlattenFoldersOnExtract;
zip.FlattenFoldersOnExtract = true;
zip.ExtractAll();
zip.FlattenFoldersOnExtract = flattenFoldersOnExtract;
You'll need to remove the directory part of the filename just prior to unzipping...
using (var zf = Ionic.Zip.ZipFile.Read(zipPath))
{
zf.ToList().ForEach(entry =>
{
entry.FileName = System.IO.Path.GetFileName(entry.FileName);
entry.Extract(appPath);
});
}
You can use the overload that takes a stream as a parameter. In this way you have full control of path where the files will be extracted to.
Example:
using (ZipFile zip = new ZipFile(ZipPath))
{
foreach (ZipEntry e in zip)
{
string newPath = Path.Combine(FolderToExtractTo, e.FileName);
if (e.IsDirectory)
{
Directory.CreateDirectory(newPath);
}
else
{
using (FileStream stream = new FileStream(newPath, FileMode.Create))
e.Extract(stream);
}
}
}
That will fail if there are 2 files with equal filenames. For example
files\additionalfiles\file1.txt
temp\file1.txt
First file will be renamed to file1.txt in the zip file and when the second file is trying to be renamed an exception is thrown saying that an item with the same key already exists