I don't get an error, but the extension isn't changed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string filename;
string[] filePaths = Directory.GetFiles(#"c:\Users\Desktop\test\");
Console.WriteLine("Directory consists of " + filePaths.Length + " files.");
foreach(string myfile in filePaths)
filename = Path.ChangeExtension(myfile, ".txt");
Console.ReadLine();
}
}
}
Path.ChangeExtension only returns a string with the new extension, it doesn't rename the file itself.
You need to use System.IO.File.Move(oldName, newName) to rename the actual file, something like this:
foreach (string myfile in filePaths)
{
filename = Path.ChangeExtension(myfile, ".txt");
System.IO.File.Move(myfile, filename);
}
Ìf you want to change the extension of a file, call File.Move().
This only changes extension of path and not of file.
Reason: Since ChangeExtension is called of Path.ChangeExtension. For file, use System.IO. File Class and its methods.
The documentation for method ChangeExtension says that:
Changes the extension of a path string.
It doesn't say that it changes extension for a file.
I think this is roughly equivalent (correct) code:
DirectoryInfo di = new DirectoryInfo(#"c:\Users\Desktop\test\");
foreach (FileInfo fi in di.GetFiles())
{
fi.MoveTo(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length - 1) + ".txt"); // "test.bat" 8 - 3 - 1 = 4 "test" + ".txt" = "test.txt"
}
Console.WriteLine("Directory consists of " + di.GetFiles().Length + " files.");
Console.ReadLine();
Related
So I am writing a C# program which combines several text files into one and saves them as a combined text file. One issue I am having, I have a textfield which selects the intended folder the save the compiled reciept, however when selecting the desired folder, it generates a file name to the text box, the filename follwing the final / must be erased every time for the save function to work properly. I am wondering, how to remove all text after the final letter before the last / in the file directory?
Here is the code:
private void RecieptDisplayed_TextChanged(object sender, EventArgs e)
{
try
{
string[] fileAry = Directory.GetFiles(RecieptSelect.Text);
string input = RecieptSelect.Text;
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index);
MessageBox.Show("Reciepts being processed : " + index);
using (TextWriter tw = new StreamWriter(savefileas.Text + "RecieptsCombined.txt", true))
{
foreach (string filePath in fileAry)
{
using (TextReader tr = new StreamReader(filePath))
{
tw.WriteLine("Reciept for: " + " " + filePath + tr.ReadToEnd()) ;
tr.Close();
tr.Dispose();
}
MessageBox.Show("File Processed : " + filePath);
}
tw.Close();
tw.Dispose();
}
}
You have a string like
var fullpath = #"C:\temp\myfile.txt";
You can use:
var dir = Path.GetDirectoryName(fullpath);
To get
c:\temp
Note that if the path ends with a slash it doesn't remove it before "going up a directory" so c:\temp\ becomes c:\temp. Try to keep your paths free of trailing slashes
Try to always use the Path class when manipulating string that are paths. It has a whole load of useful methods (this isn't an exhaustive list but the ones I use most) like:
GetFileName
GetFileNameWithoutExtension
GetExtension
ChangeExtension
Combine
This last one builds paths, eg:
Path.Combine("c:", "temp", "myfile.txt");
It knows the different operating systems it runs on and builds paths appropriately - if you're using net core on Linux it uses "/" instead of "\" for example. full docs here
Construct a FileInfo object from the string and then use DirectoryName or Directory.
Also, do not concatenate strings to get a file name, use Path.Combine instead.
You are looking for Directory name from given path, you can use existing function to get the directory name, Path.GetDirectoryName()
using System.IO;
...
//Get the directory name
var directoryName = Path.GetDirectoryName(savefileas.Text);
using (TextWriter tw = new StreamWriter(Path.Combine(directoryName, "RecieptsCombined.txt"), true))
{
foreach (string filePath in fileAry)
{
using (TextReader tr = new StreamReader(filePath))
{
tw.WriteLine("Reciept for: " + " " + filePath + tr.ReadToEnd()) ;
tr.Close();
tr.Dispose();
}
MessageBox.Show("File Processed : " + filePath);
}
tw.Close();
tw.Dispose();
}
I have write a c# code to retrieve all the file names follow by printing one of the information inside. Example File contains (file1.mht, file2.mht, file3.mht). Maybe the contain inside is (aaaaaa, bbbbbb, cccccc) follow the sequence of the file.
Example out output:
file1.mht aaaaaa
file2.mht bbbbbb
file3.mht cccccc
But I encounter the problem it cannot loop the file name follow by showing the content inside. Anyone can helps? Current result is it show all the directory first and only done the work for the first one in directory.
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Specialized;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
string str = "";
string mht_text = "";
string directory = "";
string listInfo = "";
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
foreach (char filePath in directory)
{
//Here is my work to retrieve the data in the file
Console.WriteLine("Names:" + str + " " + "Component:" + component);
Console.ReadKey();
}
}
}
}
From your question I understand that you want to print the file name followed by the content of the same, if so you can try:
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
foreach (FileInfo file in Files)
{
// read the content of the file
var content = File.ReadAllText(file.FullName);
// from your question "Example out output: file1.mht aaaaaa"
Console.WriteLine($"{file.Name} {content}");
}
only done the work for the last one in directory.
Yes, that's cause your directory variable is a string string directory = "" which will get overridden by the last value of loop iteration. You rather want to store in a string[] rather if you want to process all of them.
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
Please try this.
foreach (FileInfo file in Files)
{
str = file.Name;
directory += mht_file + str;
Console.WriteLine(directory);
}
i am trying to concatenate an address whose 1 part is being fetched at line 15 of the following code and another part from line 19.. i want to add the address separator "\" symbol in between both .. but i am not able to due to some error.. can anyone help me in this.. thank you..:)
here is my code
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;
namespace freshtry
{
class Program
{
static void Main(string[] args)
{
int count = 0;
string[] filepath= Directory.GetFiles(#"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\output\msvs", "*.wav");
string folder1 = #"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\output\msvs";
foreach(string file in filepath)
{
//string addr = "\";
string filename = System.IO.Path.GetFileName(file);
string filename1 = folder1 + "\" + filename;
Console.WriteLine(filename1);
//string.Concat(folder1,"\");
count++;
}
//Console.WriteLine(count);
Console.ReadLine();
}
}
}
and one more thing i don't want to add any additional directories which don't work with .net 2.0.:)
The code here:
string filename1 = folder1 + "\" + filename;
is invalid, as \ is an escape character. You can either escape the backslash, using \\, or use the # symbol to prevent escaping: #"\".
You could also look at the Path.Combine() method, which is a better way to achieve this.
simple answer: Use double backslash
string filename1 = folder1 + "\\" + filename;
Better answer: Use
string filename1 = Path.Combine(folder1, filename);
You need to do like
string filename1 = folder1 + "\\" + filename;
Or
string filename1 = string.Concat(folder1, "\\", filename);
I'm working with the .NET Compact Framework 3.5 and want to delete some specific folders and their subfolders. When I run the app it gives IO exception. I've tried to use Directory.Delete(path) method but it didn't work.
How can I solve this problem?
Here is my code :
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Reset_Client
{
static class Program
{
static void Main(){
myfunc();
MessageBox.Show("Cihaz resetlendi!");
}
public static void myfunc()
{
string mainPath = #"\Storage Card\deneme";
try
{
DeleteDirectory(mainPath + "CRM");
DeleteDirectory(mainPath + "BHTS");
DeleteDirectory(mainPath + "IMAGES");
DeleteDirectory(mainPath + "STYLES");
DeleteDirectory(mainPath + "TABLES");
DeleteDirectory(mainPath + "LOG");
File.Delete(mainPath + "Agentry.ini");
File.Delete(mainPath + "Agentry.app");
File.Delete(mainPath + "Agentry.usr");
}
catch (IOException e)
{
myfunc();
}
}
public static void DeleteDirectory(string target_dir)
{
FileInfo fileInfo = new FileInfo(target_dir);
FileAttributes attributes = fileInfo.Attributes;
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// set the attributes to nonreadonly
fileInfo.Attributes &= ~FileAttributes.ReadOnly;
}
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
}
}
Why not delete the directory recursively:
Directory.Delete(path, true);
See here.
Also, see here as it may be similar to what you are encountering.
Try this..
var dir = new DirectoryInfo(#FolderPath);
dir.Delete(true);
You are not telling what kind of IO exception you are getting, Are you missing a backslash () in your path?
mainPath + "CRM" becomes "\Storage Card\denemeCRM" and not "\Storage Card\deneme\CRM"
I'm creating C# console app to clean up my download folder in windows
my app work fine for video file and move and and delete it from download folder. but how can I make get get the file in subfolder and add it to my files array?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace CleanDownloadFolder
{
class Program
{
static void Main(string[] args)
{
string sourcePath = #"C:\Users\___\Downloads";
string targetPath = #"C:\Users\__\Videos";
CopyDirectory(sourcePath, targetPath);
}
private static void CopyDirectory(string sourcePath, string targetPath)
{
// 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);
}
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
string fileName = null;
string destFile = null;
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
if (Path.GetExtension(fileName) == ".avi")
{
System.IO.File.Copy(s, destFile, true);
System.IO.File.Delete(s);
}
}
}
}
}
}
Directory.GetFiles has an overload that could be used to get the list of files in subdirectories
string[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
The remainder of your code should work as is, however, if your are interested only in the AVI files then you could put that extension directly in the GetFiles call. In that way you get only AVI files and your code could be simplified removing the if
string[] files = Directory.GetFiles(sourcePath. "*.AVI", SearchOption.AllDirectories);
string fileName = null;
string destFile = null;
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = Path.GetFileName(s);
destFile = Path.Combine(targetPath, fileName);
File.Copy(s, destFile, true);
File.Delete(s);
}
I suggest also to add a using System.IO; at the top of your code file to avoid all of that full namespace typing required without the using