I have a folder with .pdf files. In the names of most files I want to replace specific string with another string.
Here's what I've written.
private void btnGetFiles_Click(object sender, EventArgs e)
{
string dir = tbGetFIles.Text;
List<string> FileNames = new List<string>();
DirectoryInfo DirInfo = new DirectoryInfo(dir);
foreach (FileInfo File in DirInfo.GetFiles())
{
FileNames.Add(File.Name);
}
lbFileNames.DataSource = FileNames;
}
Here I extract all file names in List Box.
private void btnReplace_Click(object sender, EventArgs e)
{
string strReplace = tbReplace.Text; // The existing string
string strWith = tbWith.Text; // The new string
string dir = tbGetFIles.Text;
DirectoryInfo DirInfo = new DirectoryInfo(dir);
FileInfo[] names = DirInfo.GetFiles();
foreach (FileInfo f in names)
{
if(f.Name.Contains(strReplace))
{
f.Name.Replace(strReplace, strWith);
}
}
And here I want to do the replacing, but something is going wrong. What?
It sounds like you want to change the name of the file on disk. If so then you need to use the File.Move API vs. changing the actual string which is the file name.
One other mistake you are making is the Replace call itself. A string in .Net is immutable and hence all of the mutating APIs like Replace return a new string vs. changing the old one in place. To see the change you need to assign the new value back to a variable
string newName = f.Name.Replace(strReplace, strWith);
File.Move(f.Name, newName);
f.Name is a read-only property. f.Name.Replace(..) simply returns a new string with the filename you want, but never actually changes the file.
I suggest something along the following, though I haven't tested it:
File.Move(f.Name, f.Name.Replace(strReplace, strWith));
Replace return another string, it doesn't change the original string.
So you need to write
string newName = f.Name.Replace(strReplace, strWith);
of course this doesn't change the name of the file on disk.
If that was your intention then you should look at
File.Move(f.Name, newName);
also keep in mind that File.Move will fail with an exception if the destination file exists.
See here for an example
At a first glance, seems like you're not reassigning the replaced string to your f.Name variable. Try this:
string NewFileName = f.Name.Replace(strReplace, strWith);
File.Copy(f.Name, NewFileName);
File.Delete(f.Name);
When you call string.Replace this doesn't alter your existing string. Instead it is returning a new string.
You need to change your code to something like this:
if(f.Name.Contains(strReplace))
{
string newFileName = f.Name.Replace(strReplace, strWith);
//and work here with your new string
}
Related
I need to search a String in a text file that the content in the text file will always be appended(in other method). For example String "abcdefg" need to be search exactly same in the file.
ArrayList<String> List = new ArrayList<String>();
FileReader filereader = new FileReader(file);
BufferedReader bufferreader = new BufferedReader(filereader);
String linetxt;
while((linetxt = bufferreader.readLine())!=null)
{
List.add(linetxt);
List.add("\r\n");
}
System.out.println("Please enter a string: ");
String usern = input.next();
System.out.println(List);
if ((List.contains(usern.substring(0,usern.length()))));
{
System.out.println("String existed.");
}
bufferreader.close();
The Test File current content (will always be added new content):
abcde12345
This is my code, but it occurs a problem that I will always get "String existed" no matter what I input(the String I input is not in the text file but it still printing that the String existed).
How can I modify my code to make that if my input is contained in the ArrayList, it will return "String existed"?
Is it any other ways to search a String in a text file(the content of text file will be appended in other method)?
Thanks.............. Hope everyone safe.
So I have a program that turns a .txt file into a string to then send it via bluetooth to a printer, the problem is that right now I'm doing it using the file name but I wanted to do it only using the path of the file, this has to do with the fact that I need to search on the folder for any existing txt files and if there are any I need to print the first one and then delete it, so I can't be doing it by using the file's name. This is my code so far:
private fun readFile() String {
val file = File(storage/emulated/0/IS4-PDF-RDP/00233116695912019091310005913BLUETOOTH.txt)
var ins InputStream = file.inputStream()
read contents of IntputStream to String
var content = ins.readBytes().toString(Charset.defaultCharset())
return content
}
You can find the first file in the folder read it and then delete it as per your requirements
File("/storage/emulated/0/IS4-PDF-RDP/").walk().find {
it.extension == "txt"
}?.apply {
inputStream().readBytes().toString(Charset.defaultCharset())
delete()
}
First of all, I don't have any code to show yet, but the idea is that there is a text document that contains information, say... 'John Fitzgerald New York' on a single line, and I want to find that via .contains(), for example:
Scanner newScanner = new Scanner(inputFile);
String name = "Fitzgerald";
while(!newScanner.nextLine().contains(name)){
}
The idea being that I can then save the entire line as a variable. A search for Fitzgerald should allow me to save John Fitzgerald New York as a variable, in other words. Any ideas?
Scanner sc = new Scanner(new File("input.txt")); // Read from file
final String pattern = "Fitzgerald"
while( sc.hasNext() ){ // While you still have more data
String l = sc.next(); // Get the next token
if( l.contains(pattern) ){ // Check if it matches your pattern
System.out.println("Match Found");
}
}
This is how you would do it if you want to loop over the tokens. Alternatively, you can use the next(Pattern) method if you want to find more complex patterns.
For a text document, consider using a FileReader.
final String pattern = "Fitzgerald"
FileReader f = new FileReader(new File("input.txt"));
BufferedReader b = new BufferedReader(f);
String line;
while( (line=b.readLine()) != null ){
if(line.contains(pattern)){
doSomething(line);
}
}
I am writing a text file and each time i write i want to clear the text file.
try
{
string fileName = "Profile//" + comboboxSelectProfile.SelectedItem.ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), true))
{
sw.WriteLine(fileName);
MessageBox.Show("Default is set!");
}
DefaultFileName = "Default//DefaultProfile.txt";
}
catch
{
}
How do I do this? I want to remove all previous content from DefaultProfile.txt.
I actually have to know the method or way (just a name could be) to remove all content from the text file.
You could just write an empty string to the existing file:
File.WriteAllText(#"Default\DefaultProfile.txt", string.Empty);
Or change the second parameter in the StreamWriter constructor to false to replace the file contents instead of appending to the file.
You can look at the Truncate method
FileInfo fi = new FileInfo(#"Default\DefaultProfile.txt");
using(TextWriter txtWriter = new StreamWriter(fi.Open(FileMode.Truncate)))
{
txtWriter.Write("Write your line or content here");
}
The most straightforward and efficient technique is to use the StreamWriter constructor's boolean parameter. When it's set to false it overwrites the file with the current operation. For instance, I had to save output of a mathematical operation to a text file. Each time I wanted ONLY the current answer in the text file. So, on the first StreamWriter operation, I set the boolean value to false and the subsequent calls had the bool val set to true. The result is that for each new operation, the previous answer is overwritten and only the new answer is displayed.
int div = num1 / denominator;
int mod = num1 % denominator;
Console.Write(div);
using (StreamWriter writer = new StreamWriter(FILE_NAME, false ))
{
writer.Write(div);
}
Console.Write(".");
using (StreamWriter writer = new StreamWriter(FILE_NAME, true))
{
writer.Write(".");
}
You can use FileMode.Truncate. Code will look like
FileStream fs = new
FileStream(filePath, FileMode.Truncate, FileAccess.Write )
{
fs.Close();
}
System.IO.File.Delete, or one of the System.IO.FileStream constructor overloads specifying FileMode.Create
Simply change the second parameter from true to false in the contructor of StreamWriter.
using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), **false**))
See StreamWriter Contructor
How do I get the full path for a file based on first 6 letters in the filename in C#? Is there any Regex for this?
I have a folder with 500K+ images.
All the images are named as per the database column value.
I am querying the table and based on the column value I have to search the folder for the specific file.
If the column value is 209050 there will be one file in the folder like 209050.pdf or 209050_12345.pdf. There will always be one image for 209050.
Please help
var files = Directory.EnumerateFiles(#"C:\MyRootDir", "209050*", SearchOption.AllDirectories);
This will return an enumerable of strings. Each string will the full path of the file whose name matches the specified pattern, in this case, any file whose name begins with '209050', irrespective of the extension. This will even search within sub directories of the folder MyRootDir.
If you wish to only filter for jpg files, change the 2nd argument accordingly.
var files = Directory.EnumerateFiles(#"C:\MyRootDir", "209050*.jpg", SearchOption.AllDirectories);
In case you are NOT using .Net Framework 4 or 4.5, you could use the GetFiles method instead.
var files = Directory.GetFiles(#"C:\MyRootDir", "209050*.jpg", SearchOption.AllDirectories);
The following will show you all .jpg files starting with 209050 in C:\MyDirectory:
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] myFiles = Directory.GetFiles(#"C:\MyDirectory");
foreach (var x in myFiles)
{
string[] splitName = x.Split('\\');
string fileName = splitName[splitName.Length - 1];
if (fileName.StartsWith("209050") && fileName.EndsWith(".jpg"))
{
Console.WriteLine(x);
}
}
Console.ReadLine();
}
}
}
Here is my directory:
Here is the output:
Does this help?