The path of firefox history file contain a Profile Number how can i get this number dynamically in C#
C:\Users\\AppData\Roaming\Mozilla\Firefox\Profiles\.default\formhistory.sqlite
you need to read profiles.ini file and catch the default profile
using System;
using System.Linq;
using System.IO;
namespace Firefox
{
class Reader
{
public static string ReadFirefoxProfile()
{
string apppath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string mozilla = System.IO.Path.Combine(apppath, "Mozilla");
bool exist = System.IO.Directory.Exists(mozilla);
if (exist)
{
string firefox = System.IO.Path.Combine(mozilla, "firefox");
if (System.IO.Directory.Exists(firefox))
{
string prof_file = System.IO.Path.Combine(firefox, "profiles.ini");
bool file_exist = System.IO.File.Exists(prof_file);
if (file_exist)
{
StreamReader rdr = new StreamReader(prof_file);
string resp = rdr.ReadToEnd();
string[] lines = resp.Split(new string[] { "\r\n" }, StringSplitOptions.None);
string location = lines.First(x => x.Contains("Path=")).Split(new string[] { "=" }, StringSplitOptions.None)[1];
string prof_dir = System.IO.Path.Combine(firefox, location);
return prof_dir;
}
}
}
return "";
}
}
}
You can read out the following ini file which contains the profile names of every firefoxprofile:
"C:\Users\Username\AppData\Roaming\Mozilla\Firefox\profiles.ini"
Click the Windows Start button and type %APPDATA%\Mozilla\Firefox\Profiles\ in the Search box at the bottom of the Start menu, without pressing Enter. A list of profiles will appear at the top of the Start menu.
Click on the profile with “default” in the name to open it in a window.
Related
I currently have 2 folders on my desktop "START" and "END".
There could be any number of files in start folder but I need to figure out the following.
If the filenames exist in the START FOLDER then check if they exist in the END Folder and if they do COPY the files that exist.
I have stated the strings in the code and have used GetFiles to find the file names in each folder. But cant piece it together ...
var USERNAME = Environment.UserName;
string START_DIRECTORY = #"C:\Users\" + USERNAME + "\\Desktop\\START";
string END_FOLDER_STRING = #"C:\Users\" + USERNAME + "\\Desktop\\END";
string[] files = System.IO.Directory.GetFiles(START_DIRECTORY);
string[] files2 = System.IO.Directory.GetFiles(END_FOLDER_STRING);
Try using LINQ, because most of the times it is faster than iterating through both collections:
First, add a class called FileNameEqualityComparer.
This class will be used to compare the elements to see if they are the same. In your case, if their file name is equal it should return true:
public class FileNameEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (ReferenceEquals(x, y))
{
return true;
}
return x != null && y != null && Path.GetFileName(x) == Path.GetFileName(y);
}
public int GetHashCode(string obj)
{
return Path.GetFileName(obj).GetHashCode();
}
}
And then use IEnumerable.Intersect with the created IEqualityComparer to get the files shared by your two collections:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
...
static void Main(string[] args)
{
var USERNAME = Environment.UserName;
string START_DIRECTORY = #"C:\Users\" + USERNAME + "\\Desktop\\START";
string END_FOLDER_STRING = #"C:\Users\" + USERNAME + "\\Desktop\\END";
IEnumerable<string> startFiles = Directory.GetFiles(START_DIRECTORY);
IEnumerable<string> endFiles = Directory.GetFiles(END_FOLDER_STRING);
foreach(string file in startFiles.Intersect(endFiles, new FileNameEqualityComparer()))
{
File.Copy(file, "[the path to the folder where they should be copied]");
}
}
The simplest thing: iterate over every file in START_DIRECTORY and check if a correcposing file exists in end files. If it does, copy it. Beware that performacewise this is not the best solution
static void Main(string[] args)
{
var USERNAME = Environment.UserName;
string START_DIRECTORY = #"C:\Users\" + USERNAME + "\\Desktop\\START";
string END_FOLDER_STRING = #"C:\Users\" + USERNAME + "\\Desktop\\END";
string[] startFiles = System.IO.Directory.GetFiles(START_DIRECTORY);
string[] endFiles = System.IO.Directory.GetFiles(END_FOLDER_STRING);
//for every file in start files
foreach (var startFile in startFiles)
{
//get its name
var startFileName = Path.GetFileName(startFile);
//and try to get a file with the same name in end file
var correspondingFineInEndFiles = endFiles.FirstOrDefault(endfile => Path.GetFileName(endfile) == startFileName);
//if the file in end file does exist
if (correspondingFineInEndFiles != null)
{
//copy it, and override the old file
File.Copy(startFile, correspondingFineInEndFiles, true);
}
}
}
I'm stuck here while opening and reading csv file in c# program. Ive just started working upon ILNumerics to display 3D matrix graph, but the Exception rises with
"Could not find file 'C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv'."
Please help me out!
Below is the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using ILNumerics;
using ILNumerics.Drawing;
using ILNumerics.Drawing.Plotting;
namespace martix
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ilPanel1_Load(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string path = #"C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv";
StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
string dataLines = string.Empty;
while (sr.Peek() != -1)
dataLines += sr.ReadLine().Replace(";", ",") + "\n";
sr.Close();
dataLines = dataLines.Trim('\n');
//Convert the data-string into an ILArray
ILArray<int> AN = ILMath.csvread<int>(dataLines);
//Create a new scene, which is the base for our graph
var scene = new ILScene();
using (ILScope.Enter())
{
//Convert all data points to float
ILArray<float> A = ILMath.tosingle(AN);
//Add a plot to the scene and configure it
scene.Add(new ILPlotCube
{
//Render in 3D
TwoDMode = false,
//Add 3 axes
Axes =
{
XAxis =
{
Label = { Text = "Price in $" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
YAxis =
{
Label = { Text = "Rating count" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
ZAxis =
{
Label = { Text = "Download count" }
}
},
//Add the data points
Children = {
new ILPoints {
Positions = A
},
},
//Set start rotation for 3D rendered graph
Rotation = Matrix4.Rotation(new Vector3(1, 1, 1), 0.5f)
});
}
//Add the scene to the ILPanel
ilPanel1.Scene = scene;
}
}
}
It may be the spaces you have in the path. Nevermind, you're using verbatim string.
Are you sure that path is accessible and is not a networked mapped path? Can you move your file temporarily? It really seems that you don't have access to that path.
Also you should try doing the following to pinpoint the issue:
System.IO.FileInfo fi = null;
try
{
fi = new System.IO.FileInfo(path);
}
catch (ArgumentException) {... }
catch (System.IO.PathTooLongException) {... }
catch (NotSupportedException) {... }
if (ReferenceEquals(fi, null))
{
...
// file name is not valid
}
else
{
...
// file name is valid... May check for existence by calling fi.Exists.
}
EDIT:
use System.IO.Directory.GetFiles to list the exact names of the files in that folder, it may be that the file name is different (stats.csv.csv) and window explorer is hiding the extension.
Got the solution while trying. I created the csv file programatically and this time it read the file.
Just added the few line before the path and modified the path.
StringBuilder csv = new StringBuilder();
csv.AppendLine("112,113,222");
string csvpath = #"C:\\stats\xyz.csv";
File.AppendAllText(csvpath,csv.ToString());
string path = #"C:\stats\xyz.csv";
And thats it. Anyways Thanks for helping :)
I have created something that grabs all file names that have the extension .lua with them. This will then list them in a CheckListBox. Everything goes well there but I want to know which one of the CheckListBox's are ticked/checked and then open them in notepad.exe.
To dynamically add the files Code (works perfectly, and adds the files i want)
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appData + "\\Lua";
string[] fileArray = Directory.GetFiles(path, "*.lua");
for (int i = 0; i < fileArray.Length; i++)
{
string Name = Path.GetFileName(fileArray[i]);
string PathToLua = fileArray[i];
ScriptsBoxBox.Items.AddRange(Name.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
Console.WriteLine(fileArray[i]);
}
Then when i check the items i want to open in notepad i use `
System.Diagnostics.Process.Start("notepad.exe", ScriptsBoxBox.CheckedItems.ToString());
Or
System.Diagnostics.Process.Start("notepad.exe", ScriptsBoxBox.CheckedItems);
Neither works and im pretty sure it's on my end. So my problem is that i cannot open the file that is ticked/checked in checklistbox and want to resolve this problem. However when I do
System.Diagnostics.Process.Start("notepad.exe", PathToLua);
It opens the files with .lua extension ticked or not which makes sense.
I don't think there are any arguments that you can pass to notepad to open a list of specific files. However, you can use a loop to open each file.
foreach (var file in ScriptsBoxBox.CheckedItems)
{
System.Diagnostics.Process.Start("notepad.exe", file);
}
I don't know WinForms as well as WPF but here goes
You need an object that contains your values
public class LuaFile
{
public string FileName { get; set; }
public string FilePath { get; set; }
public LuaFile(string name, string path)
{
FileName = name;
FilePath = path;
}
public override string ToString()
{
return FileName;
}
}
Replace your for loop with
foreach (var file in files)
{
ScriptsBoxBox.Items.Add(new LuaFile(Path.GetFileName(file), file));
}
And to run the checked files
foreach (var file in ScriptsBoxBox.CheckedItems)
{
System.Diagnostics.Process.Start("notepad.exe", ((LuaFile)file).FilePath);
}
Thanks everyone that helped but I solved it on my own (pretty easy when you read :P)
For anyone in the future that wants to do this here is how i accomplished it.
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appData + "\\Lua";
string[] fileArray = Directory.GetFiles(path, "*.lua");
for (int i = 0; i < fileArray.Length; i++)
{
string Name = Path.GetFileName(fileArray[i]);
string PathToLua = fileArray[i];
//ScriptsBoxBox.Items.AddRange(Name.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
// Console.WriteLine();
Console.WriteLine(ScriptsBoxBox.CheckedItems.Contains(Name));
var pathname = ScriptsBoxBox.CheckedItems.Contains(Name);
if (ScriptsBoxBox.CheckedItems.Contains(Name))
{
System.Diagnostics.Process.Start("notepad.exe", fileArray[ScriptsBoxBox.CheckedItems.IndexOf(Name)]); // I supposed this would get the correct name index, and it did! fileArray by default seems to get the path of the file.
}
What I want to do is actually have my program open up and set a string array so that i can use it for if commands (its used to block people) and I want to store another string in there so that it can be saved and still be used if the program restart. Can someone show me how to do this? Please and thank you :]
You could use the following:
string[] lines = File.ReadAllLines(#"Path here").ToArray();
This splits each line up into the array.
As for saving to file, google "saving to file in c#", you will get plenty of results and tutorials.
This is definitely better then the solution I posted first:
File.WriteAllLines(fileName, yourStringArray);
yourStringArray = File.ReadAllLines(fileName);
File.WriteAllLines
File.ReadAllLines
Below my first answer. Correct, but crap!
Something like this should work for you. Don't blame me for inaccuracy, I am not wide awake yet! ;)
{
string fileName = #"d:\temp\blacklist.txt";
char seperator = ';';
public Form1()
{
InitializeComponent();
string[] users = { "Dave", "John", "Shawn" };
//Save(users);
users = Load();
}
public string[] Load()
{
string line;
using (StreamReader sr = new StreamReader(this.fileName))
{
line = sr.ReadToEnd();
}
return line.Split(seperator);
}
public void Save(string[] users)
{
using (StreamWriter sw = new StreamWriter(this.fileName))
{
string line = string.Empty;
foreach (string user in users)
{
line += string.Format("{0}{1}", user, seperator);
}
sw.WriteLine(line);
sw.Flush();
}
}
}
Firstly, i'd just like to mention that I've only started learning C# a few days ago so my knowledge of it is limited.
I'm trying to create a program that will parse text files for certain phrases input by the user and then output them into a new text document.
At the moment, i have it the program searching the original input file and gathering the selected text input by the user, coping those lines out, creating new text files and then merging them together and also deleting them afterwards.
I'm guessing that this is not the most efficient way of creating this but i just created it and had it work in a logical manor for me to understand as a novice.
The code is as follows;
private void TextInput1()
{
using (StreamReader fileOpen = new StreamReader(txtInput.Text))
{
using (StreamWriter fileWrite = new StreamWriter(#"*DIRECTORY*\FIRSTFILE.txt"))
{
string file;
while ((file = fileOpen.ReadLine()) != null)
{
if (file.Contains(txtFind.Text))
{
fileWrite.Write(file + "\r\n");
}
}
}
}
}
private void TextInput2()
{
using (StreamReader fileOpen = new StreamReader(txtInput.Text))
{
using (StreamWriter fileWrite = new StreamWriter(#"*DIRECTORY*\SECONDFILE.txt"))
{
string file;
while ((file = fileOpen.ReadLine()) != null)
{
if (file.Contains(txtFind2.Text))
{
fileWrite.Write("\r\n" + file);
}
}
}
}
}
private static void Combination()
{
ArrayList fileArray = new ArrayList();
using (StreamWriter writer = File.CreateText(#"*DIRECTORY*\FINALOUTPUT.txt"))
{
using (StreamReader reader = File.OpenText(#"*DIRECTORY*\FIRSTFILE.txt"))
{
writer.Write(reader.ReadToEnd());
}
using (StreamReader reader = File.OpenText(#"*DIRECTORY*\SECONDFILE.txt"))
{
writer.Write(reader.ReadToEnd());
}
}
}
private static void Delete()
{
if (File.Exists(#"*DIRECTORY*\FIRSTFILE.txt"))
{
File.Delete(#"*DIRECTORY*\FIRSTFILE.txt");
}
if (File.Exists(#"*DIRECTORY*\SECONDFILE.txt"))
{
File.Delete(#"*DIRECTORY*\SECONDFILE.txt");
}
}
The output file that is being created is simply outputting the first text input followed by the second. I am wondering if it is possible to be able to merge them into 1 file, 1 line at a time as it is a consecutive file meaning have the information from Input 1 followed 2 is needed rather than all of 1 then all of 2.
Thanks, Neil.
To combine the two files content in an one merged file line by line you could substitute your Combination() code with this
string[] file1 = File.ReadAllLines("*DIRECTORY*\FIRSTFILE.txt");
string[] file2 = File.ReadAllLines("*DIRECTORY*\SECONDFILE.txt");
using (StreamWriter writer = File.CreateText(#"*DIRECTORY*\FINALOUTPUT.txt"))
{
int lineNum = 0;
while(lineNum < file1.Length || lineNum < file2.Length)
{
if(lineNum < file1.Length)
writer.WriteLine(file1[lineNum]);
if(lineNum < file2.Length)
writer.WriteLine(file2[lineNum]);
lineNum++;
}
}
This assumes that the two files don't contains the same number of lines.
try this method. You can receive three paths. File 1, File 2 and File output.
public void MergeFiles(string pathFile1, string pathFile2, string pathResult)
{
File.WriteAllText(pathResult, File.ReadAllText(pathFile1) + File.ReadAllText(pathFile2));
}
If the pathResult file exists, the WriteAllText method will overwrite it. Remember to include System.IO namespace.
Important: It is not recommended for large files! Use another options available on this thread.
If your input files are quite large and you run out of memory, you could also try wrapping the two readers like this:
using (StreamWriter writer = File.CreateText(#"*DIRECTORY*\FINALOUTPUT.txt"))
{
using (StreamReader reader1 = File.OpenText(#"*DIRECTORY*\FIRSTFILE.txt"))
{
using (StreamReader reader2 = File.OpenText(#"*DIRECTORY*\SECONDFILE.txt"))
{
string line1 = null;
string line2 = null;
while ((line1 = reader1.ReadLine()) != null)
{
writer.WriteLine(line1);
line2 = reader2.ReadLine();
if(line2 != null)
{
writer.WriteLine(line2);
}
}
}
}
}
Still, you have to have an idea how many lines you have in your input files, but I think it gives you the general idea to proceed.
Using a FileInfo extension you could merge one or more files by doing the following:
public static class FileInfoExtensions
{
public static void MergeFiles(this FileInfo fi, string strOutputPath , params string[] filesToMerge)
{
var fiLines = File.ReadAllLines(fi.FullName).ToList();
fiLines.AddRange(filesToMerge.SelectMany(file => File.ReadAllLines(file)));
File.WriteAllLines(strOutputPath, fiLines.ToArray());
}
}
Usage
FileInfo fi = new FileInfo("input");
fi.MergeFiles("output", "File2", "File3");
I appreciate this question is almost old enough to (up)vote (itself), but for an extensible approach:
const string FileMergeDivider = "\n\n";
public void MergeFiles(string outputPath, params string[] inputPaths)
{
if (!inputPaths.Any())
throw new ArgumentException(nameof(inputPaths) + " required");
if (inputPaths.Any(string.IsNullOrWhiteSpace) || !inputPaths.All(File.Exists))
throw new ArgumentNullException(nameof(inputPaths), "contains invalid path(s)");
File.WriteAllText(outputPath, string.Join(FileMergeDivider, inputPaths.Select(File.ReadAllText)));
}