I've honestly been researching about this for hours, and I still haven't found anything close to what I am looking for.
Basically I created a folder in my project and called it "Files". Then I added a lot of actual files to that folder, and now I want to access them via a void, but I can't get the names of them.
I've tried to display the files in a message box (just for testing purposes), so I used this:
public static string[] GetResourceNames()
{
var asm = Assembly.GetEntryAssembly();
string resName = asm.GetName().Name + ".Files";
using (var stream = asm.GetManifestResourceStream(resName))
using (var reader = new System.Resources.ResourceReader(stream))
{
return reader.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).ToArray();
}
}
But all it does is return an error saying the reader can't be null.
I'm trying to show it in a foreach loop like this:
foreach (string resourceName in GetResourceNames())
{
MessageBox.Show(resourceName);
}
but it shows nothing.
What I'm trying to do is this:
Assembly assembly = Assembly.GetExecutingAssembly();
int totalFiles = 17;
int currentFiles = 0;
foreach (var file in assembly.GetManifestResourceNames())
{
string extractPath = functions.pathToExtract + #"\" + file;
using (Stream s = assembly.GetManifestResourceStream(file))
using (BinaryReader r = new BinaryReader(s))
using (FileStream fs = new FileStream(extractPath, FileMode.OpenOrCreate))
using (BinaryWriter w = new BinaryWriter(fs))
w.Write(r.ReadBytes((int)s.Length));
currentFile.Invoke((MethodInvoker)delegate { currentFile.Text = "Installing : " + file + " ( " + currentFiles + " out of "+ totalFiles + " installed )"; });
currentFiles += 1;
}
This is what I'm trying to do, and this is code is successful, but it writes the file names as: SolutionName.Files.FileName.Extension and I only want it to write as FileName.Extension
What am I doing wrong here?
Well, a resource file is stored with the format you've specified: [Solution].[Folder].[File].[Extension].
Assuming all you really want to do is remove the initial [Solution].[Folder] from file names you can just use String.Replace.
Something like:
var fileName = file.Replace("[Solution].[Folder]", "");
Then use fileName for the currentFile.Text or for extractPath. Be mindful that I don't know what functions.pathToExtract + #"\" + file in your code produces at the moment, so it's a bit of a guess on my part, but I think this would produce a sensible path which could be used for extracting embedded resources.
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 am trying to create a console app on network version 5.0 using visual studio. The purpose is to read all the PNG files in a directory, and make a JSON file with the code:
{
"format_version": "1.16.100",
"minecraft:texture_set": {
"color": "*Filename*",
"metalness_emissive_roughness": "*Filename_mer*"
}
}
In it. And yes this is for Minecraft. The filename and the filename_mer are automatically filled in by code, but that isn't my issue.
static void Main(string[] args)
{
Console.WriteLine("Goto " + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Packages\\Microsoft.MinecraftUWP_8wekyb3d8bbwe\\LocalState\\games\\com.mojang\\resource_packs" + " And find the resource pack you want to generate files into");
string pathname = Console.ReadLine();
#region Message
Console.WriteLine();
Console.WriteLine("Looking for folder...");
#endregion
string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Packages\\Microsoft.MinecraftUWP_8wekyb3d8bbwe\\LocalState\\games\\com.mojang\\resource_packs\\" + pathname + "\\textures";
#region Message
Console.WriteLine();
Console.WriteLine("Folder found in");
Console.WriteLine(path);
#endregion
string[] directories = Directory.GetDirectories(path);
foreach (string paths in directories)
{
string[] files = Directory.GetFiles(paths);
foreach (string file in files)
{
string filenameWithType = file.Substring(file.LastIndexOf("\\") + 1);
string filename = filenameWithType.Substring(0, filenameWithType.LastIndexOf("."));
string thisPath = file.Substring(0, file.LastIndexOf("\\"));
if (filenameWithType.Substring(filenameWithType.LastIndexOf(".") + 1) == "png")
{
string newPath = thisPath + "\\" + filename + ".texture_set.json";
File.Create(newPath);
List<string> codeInFile = new List<string>();
codeInFile.Clear();
codeInFile.Add("{");
codeInFile.Add("\"format_version\": \"1.16.100\",");
codeInFile.Add("\"minecraft:texture_set\": {");
codeInFile.Add("\"color\": \"" + filename + "\",");
codeInFile.Add("\"metalness_emissive_roughness\": \"" + filename + "_mer\"");
codeInFile.Add("}");
codeInFile.Add("}");
TextWriter tw = new StreamWriter(newPath, false);
foreach (string line in codeInFile)
{
tw.WriteLine(line);
Console.WriteLine(line);
}
tw.Close();
string newPathtxt = thisPath + "\\" + filename + "_mer.png";
Bitmap bitmap = new Bitmap(file);
using (Bitmap b = new Bitmap(bitmap.Width, bitmap.Height))
{
using (Graphics g = Graphics.FromImage(b))
{
g.Clear(Color.Green);
}
b.Save(newPathtxt, ImageFormat.Png);
}
}
}
}
#region Message
Console.WriteLine("");
Console.WriteLine("All done, Your good to go!");
#endregion
Console.Read();
}
This is all my code, on the file. It reads a directory which you enter, looks through the textures file, and for each PNG file in there it creates a JSON file with the code specified earlier. Although when run the code gives me this error.
System.IO.IOException: 'The process cannot access the file 'C:\Users\https\AppData\Local\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang\resource_packs\Vanilla_Resource_Pack_1.17.10\textures\blocks\acacia_trapdoor.texture_set.json' because it is being used by another process.'
I cannot find any answers which fit my issue, I would appreciate any help.
This is a Minecraft Bedrock edition resource pack btw, not sure if that helps.
Don't do this File.Create(newPath); or rethink your problem. It looks like a typo.
In short File.Create(newPath) is creating a FileStream and discarding it, leaving the file open and with a share lock. If you are trying to pre-create the file, at least use the using statement:
using (File.Create(newPath));
or Close
File.Create(newPath).Close();
or
File.WriteAllText(newPath, String.Empty);
or
File.WriteAllBytes(newPath, Array.Empty<byte>());
If you are just trying to create or overwrite the file StreamWriter(newPath, false) is good enough.
Guys am trying to read a csv file from the view, get its data , format it and write back into an empty csv file. presently have been able to achieve the first approach, where the challenge is right now is writing back into an empty csv file created , but it happens that the csv file is always blank after writing in the file. can someone help me out if am missing anything. Note " am just reading and writing the field , have got nothing to do with the hearder because the csv file has no header" Am using csvhelper library.
if (file.ContentLength > 0)
{
string origin = "FORMATERCSV";
string destination = "FORMATERCSVDESTINATION";
string curretnDate = Convert.ToString(DateTime.Now.ToShortDateString().Replace(#"/", "_"));
var fileName = Path.GetFileName(file.FileName);
var pathfound = Server.MapPath( #"/" + "Content" + "/" + origin + "/" + curretnDate + "/");
var pathfoundDestination = Server.MapPath(#"/" + "Content" + "/" + destination + "/" + curretnDate + "/");
if (!Directory.Exists(pathfound)) Directory.CreateDirectory(pathfound);
if (!Directory.Exists(pathfoundDestination)) Directory.CreateDirectory(pathfoundDestination);
string PathToStore = string.Format(#"{0}\{1}", pathfound, fileName);
string PathToStoreDestination = string.Format(#"{0}\{1}", pathfoundDestination, fileName);
var path = Path.Combine(pathfound,fileName);
file.SaveAs(PathToStore);
file.SaveAs(PathToStoreDestination);
System.IO.File.WriteAllText(PathToStoreDestination,string.Empty);
StreamReader sr = new StreamReader(PathToStore);
CsvReader csvread = new CsvReader(sr);
csvread.Read();
var shedule = new Shedule()
{
RSA_PIN = csvread.GetField<string>(0),
EMPLOYEE_NAME = csvread.GetField<string>(1),
EMPLOYER_CONTRIBUTION = csvread.GetField<double>(2),
EMPLOYER_VC = csvread.GetField<double>(3),
EMPLOYEE_CONTRIBUTION = csvread.GetField<double>(4),
EMPLOYEE_VC = csvread.GetField<double>(5),
TOTAL_CONTRIBUTION = csvread.GetField<double>(6),
FROM_MONTH = csvread.GetField<string>(7),
FROM_YEAR = csvread.GetField<string>(8),
TO_MONTH = csvread.GetField<string>(9),
TO_YEAR = csvread.GetField<string>(10),
EMPLOYER_CODE = csvread.GetField<string>(11),
EMPLOYER_NAME = csvread.GetField<string>(12),
PTID = csvread.GetField<string>(13),
RECEIVED_DATE = csvread.GetField<string>(14),
};
StreamWriter sw = new StreamWriter(PathToStoreDestination);
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.NextRecord();
scvwrite.Flush();
// Gets field by position returning int
// var field = csv.GetField<int>(0);
}
return RedirectToAction("Index");
}
Several things could actually occure.
1) are you sure the file from the view is not empty?
2) If you use a break point when you instantiate your class Schedule. Do you get the data from the CSV.
3) Do you really need to do this 2 step, wouldn't it be better to directly write the content of the original file to the new file?
4) Last but not least don't forget to close your streamwriter or do like so :
using(var sw = new StreamWriter(PathToStoreDestination)){
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.Flush();
}
Doing so you don't even need to specify to flush.
using (var sw = new StreamWriter(PathToStoreDestination))
{
sw.AutoFlush = true;
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYER_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.NextRecord();
//scvwrite.Flush();
}
My program goes through all files in a folder, reads them, and without altering their information moves them to another location under a different name. However I cannot use the File.Move method because I get the following IOException:
The process cannot access the file because it is being used by another
process.
This is how I am reading the file and adding all its lines to a List<string>:
List<string> lines = null;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.Default))
{
lines = new List<string>();
while (!sr.EndOfStream)
lines.Add(sr.ReadLine());
}
And this is the function with which I move the file:
public static bool ArchiveFile(string filePath, string archiveFolderLocation)
{
if (!Directory.Exists(archiveFolderLocation))
Directory.CreateDirectory(archiveFolderLocation);
try
{
string timestamp = string.Format("{0:yyyy-MM-dd HHmmss}", DateTime.Now);
string newFileName = Path.GetFileNameWithoutExtension(filePath) + " " + timestamp;
string destination = string.Format("{0}\\{1}{2}", archiveFolderLocation, newFileName, Path.GetExtension(filePath));
File.Move(filePath, destination);
return true;
}
catch (Exception ex)
{
return false;
}
}
I thought using the using statement is supposed to garbage-collect and release the file after being used. How can I release the file so I can move it and why my file stays locked?
Solved:
Got it. Somewhere between these two calls I was opening a TextReaderobject without disposing it.
I thought using the using statement is supposed to garbage-collect and
release the file after being used. How can I release the file so I can
move it and why my file stays locked?
Not really. Using statement is nothing but :
try { var resource = new SomeResource(); }
finally { resource.Dispose(); // which is not GC.Collect(); }
It works fine so it looks like your file is opened from some other place in your code...
P.S.
By the way you can just do:
List<string> lines = File.ReadAllLines().ToList();
You could use:
string dpath = "D:\\Destination\\";
string spath = "D:\\Source";
string[] flist = Directory.GetFiles(spath);
foreach (string item in flist)
{
File.Move(item, dpath + new FileInfo(item).Name);
}
Replace D:\\Source & D:\\Destination\\ with the required source and destination paths, respectively.
ok i have solved my problem of finding a unique word within the file that is then used as the newly created .txt file name.
for example: current.txt files have 200 lines of words/data per file but one of the words is unique("92222225") with every current.txt file.
so the newly created output files from streamwriter becomes 92222225.txt, 933333334.txt and so on.
the whole time i though what i needed was within streamreader or streamwriter.
but what i need to add to the two was "Regex.Match".
here is the code i figured out to use for pulling strings out of a .txt file to use as a name for the output files. also to add other words to the new output file.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\reporting";
foreach (string txtName in Directory.EnumerateFiles(mydocpath, "*.txt"))
{
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader(txtName);
string content = sr.ReadToEnd();
sb.AppendLine(txtName.ToString());
sb.AppendLine("= = = = = =");
sb.Append(content);
if (content.Contains("helloworld"))
{
sb.AppendLine();
sb.AppendLine("byeworld");
}
sb.AppendLine();
sb.AppendLine();
//string fileName = content.Contains("helloworld").ToString();
string FindMatch = content;
Match match = Regex.Match(FindMatch, #"9(([A-Za-z0-9\-])\d+)");
if (match.Success)
{
//this is what adds unique word as 922225.txt file name.
string capture = match.Groups[1].Captures[0].Value;
using (StreamWriter outfile = new StreamWriter(mydocpath + #"\" + capture + ".txt"))
{
outfile.Write(sb.ToString());
}
}
}
i updated this whole post so if anyone else may need this.
never even used Regex.Match before, nor knew about it or maybe i forgot about it.
If you want to name your output file use:
using (StreamWriter outfile = new StreamWriter(mydocpath + #"\901232lOi.txt"))