I am trying to read the contents of a '.tmp' file provided as a command line argument in C#, but it either doesn't read the data or there might be some other issue:
PFB the code snippet in C# :
StreamReader inpFile2 = new StreamReader(args[1]);
string line;
while ((line = inpFile2.ReadLine()) != null) {
Console.WriteLine(line);
}
where args[1] is a.tmp file with the below contents:
Name: <<NAME>> (<<COURSE>>)
ID: <<ID>>
Total: <<TOTAL>>/100 Subtotal: <<SUBTOTAL>> Total deductions: <<LATEDEDUCTION>>
Time due: <<DUE>>
Submitted: <<SUBMITTED>>
Late minutes: <<MINUTESLATE>>
Late deduction: <<LATEDEDUCTION>>
Problem 1: <<P1>>/35
<<P1COMMENTS>>
Problem 2: <<P2>>/65
<<P2COMMENTS>>
It does not display anything.Can you point out what the problem is?I am new to C-sharp.
You can't just open a file with its name. You need its path too. Probably the current working directory.
Try changing
StreamReader inpFile2 = new StreamReader(args[1]);
To
var fileName = args[1];
var path = Path.Combine(Environment.CurrentDirectory, fileName);
StreamReader inpFile2 = new StreamReader(path);
Related
Hello I'm beginner with C# and I want to delete the last character of my file to inject JSON objects to this file manually (I know that's not the best way to do that), so I can get the right format I tried with multiple ways like open the file, manipulating the string (deleting the last character) and when I try to replace the text in that same file I have errors like IOException: The process cannot access the file 'file path' because it is being used by another process or System.UnauthorizedAccessException : 'Access to the path 'C:\Users\ASUS\Desktop\Root' is denied.
I'll show you the code :
StoreLogs Log = new StoreLogs()
{
Id = ID,
DateTime = dateT,
TaskName = task,
SrcAddress = srcPath,
DstAddress = path,
FileSize = DirSize(new DirectoryInfo(srcPath)),
DelayTransfer = ts.Milliseconds,
};
// Record JSON data in the variable
string strResultJson = JsonConvert.SerializeObject(Log);
// Show the JSON Data
// Console.WriteLine(strResultJson);
// Write JSON Data in another file
string MyJSON = null;
string strPath = #"C:\Users\ASUS\Desktop\Backup\logs\log.json";
if (File.Exists(strPath))
{
//FileInfo table = new FileInfo(strPath);
//string strTable = table.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//Console.WriteLine(erase);
//StreamReader r1 = new StreamReader(strPath);
//string strTable = r1.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//r1.Close();
using (StreamReader sr = File.OpenText(strPath))
{
string table = sr.ReadToEnd();
string erase = table.Remove(table.LastIndexOf(']'));
sr.Close();
File.WriteAllText(strPath, erase);
}
//MyJSON = "," + strResultJson;
//File.AppendAllText(strPath, MyJSON + "]");
//Console.WriteLine("The file exists.");
}
else if (!File.Exists(strPath))
{
MyJSON = "[" + strResultJson + "]";
File.WriteAllText(strPath, MyJSON);
Console.WriteLine("The file doesn't exists.");
}
else
{
Console.WriteLine("Error");
}
// End
Console.WriteLine("JSON Object generated !");
Console.ReadLine();
And that's the result I want :
[{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0}]
Edit :
Thank you all for your advices
Solution:
FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
fs.SetLength(fs.Length - 1);
fs.Close();
In the code example you have posted you are opening a stream to read the file. A using block will dispose the stream after you exit the block. You are trying to write to the file, while the read stream is still accessing it (the read stream still exists). You've basically opened the file, you read from it, and are trying to write back to it while still holding it open. The reason this is a problem is that you are not using the stream to write. So your second, write, process is unable to access the file. I see you are closing the stream prior to write, but I'm willing to bet it's still holding the reference open.
I would try this method:
How to both read and write a file in C#
what it says is the access to the path (C:\Users\ASUS\Desktop\Root) denied for the user who is running the application. for ex: If you are running from Visual studio on user1 windows login then user1 should have appropriate rights to that root folder. If the code is running by itself (exe) then check the access for that user who is invoking that exe.
Based on the errors you posted seems that:
Maybe you're leaving some stream open pointing to the file you want to edit, use the 'using' statement to avoid this (see this link for more info)
You're trying to access a file when you don't have needed permissions (you aren't a system admin or file is read-only), try changing file ubication or setting it to be writeable (see this link for mor info about the UnauthorizedAccessException exception)
Hope this helps you!
I've created a class that copies everything in the file and paste it in a different location but I want to be able to add an error message if it cannot find the file path, in case it hasn't been set up on the PC.
I'm using System.IO. So what code would I need to make this check for the file path before actually starting the class?
You could either wrap your code in a try catch, or check if the path exists.
To check if the path exists:
if(Directory.Exists(path))
{
// logic goes here
} else
{
// error message
}
Here I check the path, and if it doesn't exist, I create it, later I check if a file type txt exist, and I create it too, and write on it. Look this complement, just in case →
string path = #"c:\NewFolder";
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
path += #"\Log.txt";
if (!File.Exists(path))
{
var strFile = File.Create(path);
File.SetAttributes(path, FileAttributes.Normal);
strFile.Close();
}
using (StreamWriter sw = new StreamWriter(path, true))
{
string texto = string.Empty;
texto += "\n Date: " + DateTime.Now.ToString("yyyy/MM/dd hh:mm");
sw.WriteLine(texto);
sw.Close();
}
I have a C# program and it will not write to a file but does write to console, even though the file write line is before console. i have tried several modifications and run through debug as well, and it never writes to the file or it puts one line in the file only
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("urltest.txt");
string myFileName = String.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddhh"), "-urlcheck.log");
while((line = file.ReadLine()) != null)
{
Uri myUri = new Uri(line);
using (StreamWriter writer = new StreamWriter(myFileName))
try
{
// create the web request and response based on the url that has been
// just read from the file urltest.txt
HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(myUri);
HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
if (HttpStatusCode.OK == rspFP.StatusCode)
{
// HTTP = 200 - Internet connection available, server online
// Write status of the URL to the log file
writer.WriteLine("================================================================= =========");
writer.WriteLine("Status code of returned: OK " + myUri + " THIS URL IS NOT BLOCKED!");
Console.WriteLine("Status code of returned: OK " + myUri + " THIS URL IS NOT BLOCKED!");
var _uri = myUri.ToString();
string _catstr1 = catURL(_uri);
//regex to get the last 8-9 items of the line and replace them
Regex pat = new Regex(#"</(.*?)a");
string _catstr = pat.Replace(_catstr1, "\x20");
// Write the Catagory of the URL to file and continue
writer.WriteLine("URL " + _catstr);
Console.WriteLine("URL " + _catstr);
}
}
Most anything that writes out to a file should be either within a using block or manually fushed and closed.
using (var writer = ...)
{
// Do your writing
} // <- upon leaving the using block writer will automatically be cleaned up.
Note: I'm not a huge fan of var but as I don't know what class you're using it at least makes a valid example of code
You didn't provide the code for File access, but 99% sure that you didn't close the stream.
call Flush() if you want to force output before you close your writer
I'm developing a console application that parse xml files and generate a txt file. I have created the file path to store the new file, but this is having white spaces, like this:
string filePath = "C:\\Program Files\\my path\\fileName.txt"
but I'm creating the path using:
string filePath = Path.Combine(temp, "fileName.txt");
while temp is the previous path. And when I call:
StreamWriter sw = File.CreateText(filePath);
Is giving this exception:
Could not find a part of the path: filePath
Can someone help me with this issue?? how can I create the file with this path?
there looks like a problem with you file path
try#"C:\Program Files\my path\fileName.txt"
Note: You've updated your question with the changes mentioned in the comments.
Your issue is probably that 'my path' doesn't exist as this console application works OK for me when run as an administrator. When not run I get an UnathorizedAccessException
class Program
{
static void Main(string[] args)
{
try
{
var temp = #"C:\\Program Files\\my path\\";
string filePath = Path.Combine(temp, "fileName.txt");
StreamWriter sw = File.CreateText(filePath);
Console.WriteLine("I got here");
}
catch (Exception)
{
Console.WriteLine("I didn't");
//
}
}
}
Use this:
string filePath = #"C:\Program Files\my path\fileName.txt"
You have single backslashes in the string. Make them double backslashes:
string filePath = "C:\\Program Files\\my path\\fileName.txt"
How to prepend/append text beginning of the existing data in a text file.
Basically i need to provide a header before this data in a text file. This header is a dynamic data. Please note this data is coming from external source or SQL package or from somewhere. So After getting data in a text file then i want to provide a header text with comma separated in the existing entries/data of a text file.
I've sample data in a text file as below:
123,"SAV","CBS123",2010-10-10 00:00:00
456,"CUR","CBS456",2012-02-01 00:00:00
Header text to Prepend:
HDR<TableName><DateTime>
Output i need as below:
TableName: Account
DateTime: 2012-05-09 12:52:00
HDRAccount2012-05-09 12:52:00
123,"SAV","CBS123",2010-10-10 00:00:00
456,"CUR","CBS456",2012-02-01 00:00:00
Please help me how to get the same in both languages VB6.0, C#.NET
Note that you can't technically 'insert' into a file and have all contents 'shift' down. Best you can do is read the file and rewrite it with a new line. Here's one way to do it efficiently:
static void InsertHeader(string filename, string header)
{
var tempfile = Path.GetTempFileName();
using (var writer = new StreamWriter(tempfile))
using (var reader = new StreamReader(filename))
{
writer.WriteLine(header);
while (!reader.EndOfStream)
writer.WriteLine(reader.ReadLine());
}
File.Copy(tempfile, filename, true);
File.Delete(tempfile);
}
Credits to this answer for the idea but improved enough to make it worth posting separately.
Now if you want something that accepts the table name and date time, just add this as a second function:
static void InsertTableHeader(string filename, string tableName, DateTime dateTime)
{
InsertHeader(filename,
String.Format("HDR{0}{1:yyyy-MM-dd HH:MM:ss}",
tableName,
dateTime));
}
So just call InsertHeader(filename, "Account", DateTime.Now) or similar as needed.
var fn = #"c:\temp\log.csv";
var hdr1 = "Account";
var hdr2 = "2012-05-09 12:52:00";
System.IO.File.WriteAllText(fn, System.String.Format("HDR {0} {1}\n{2}", hdr1, hdr2, System.IO.File.ReadAllText(fn)))
String[] headerLines = new String[]{"HDR<TableName><DateTime>"};
String filename = "1.txt";
var newContent = headerLines.Union(File.ReadAllLines(filename));
File.WriteAllLines(filename, newContent);
VB6 translation of yamen's answer. Air code! I haven't compiled this, much less run
it!
Sub InsertHeader(ByVal filename As String, ByVal header As String)
Dim tempfile As String
Dim readUnit As Integer
Dim writeUnit As Integer
tempfile = "c:\tempfile" '' TODO generate better temporary filename -
'' here is a link to help with getting path of temporary directory
'' http://vb.mvps.org/samples/SysFolders
readUnit = FreeFile
Open filename For Input As #readUnit
writeUnit = FreeFile
Open tempfile For Output As #writeUnit
Print #writeUnit, header
Do Until Eof(readUnit)
Dim nextLine As String
Line Input #readUnit, nextLine
Print #writeUnit, nextLine
Loop
Close readUnit
Close writeUnit
Kill filename
FileCopy tempfile, filename
Kill tempfile
End sub
You can do it in the reverse order of the 1st answere, meanse first your write the header in text file then open that text file in append mode and then woirite the data ..for opening the file in append mode use following code line:
FileStream aFile = new FileStream(filePath, FileMode.Append,
FileAccess.Write);
StreamWriter sw = new StreamWriter(aFile);
sw.Write(text);
sw.Close();
aFile.Close();