I've created a simple class that writes and reads json data with a txt file:
using System;
using System.IO;
using Newtonsoft.Json;
namespace JsonTest1
{
class Program
{
private const string filePath = #"..\jsonData.txt";
static void Main(string[] args)
{
JsonFileTest();
NewPerson();
DeSerializer();
Console.ReadLine();
}
//Tests if the project's storage file exists.
public static void JsonFileTest()
{
bool exists = File.Exists(filePath);
if (exists)
{
Console.WriteLine("File exists at filepath " + filePath);
}
else
{
Console.WriteLine(filePath + " not found.");
}
}
//Creates a test object of 'Person' then passes it to the serializer method.
public static void NewPerson()
{
Person person = new Person();
person.Name = "John Wick";
person.Age = 999;
SerializeMethod(person);
}
//Turns an object into JSON data and writes it to file.
static void SerializeMethod(Person person)
{
File.WriteAllText(filePath, JsonConvert.SerializeObject(person));
Console.WriteLine("Test name and age copied to file.");
}
//Turns JSON data from file into an object.
static void DeSerializer()
{
Person person2 = JsonConvert.DeserializeObject<Person>(File.ReadAllText(filePath));
if (person2 != null)
{
Console.WriteLine("Json-to-C# test data: " + person2.Name + ", " + person2.Age);
}
else
{
Console.WriteLine("No data received for json-to-C# test object.");
}
}
}
}
The issue is, if I set filePath to be something like #"C:\Users\User\Documents\json.txt", then it will create a text file that I can see the data in afterwards. If filePath is local, e.g. #"..\jsonData.txt", I open the file and it's empty, even though my program can read correctly from it at runtime. Why isn't the data saving when I use the local file route?
Things I've already tried: Using a .json file instead of a .txt file. Running Visual Studio as administrator.
You're looking in the wrong folder. Your program will be executed from the bin\debug folder or something. .. then is the bin folder.
A general approach for resolving "file not found" problems is to use SysInternals Process Monitor, a free program. Add a filter with the properties Path, contains, jsonData.txt, click Add and then let your program run.
This will reveal the full path:
Then click on Jump to... in the context menu to reveal that path.
You can check the full path for any path expression like this
var fp = System.IO.Path.GetFullPath(#"..\jsonData.txt");
Related
I have the following c# Console app I would run this in ssis but i am using a couple of PDF manipulating librarys. so i am going to call an exe from my ssis package while passing in a file path.
But i am getting the following error when trying to run via the exe.
Unhandled Exception: System.IndexOutOfRangeException: Index was
outside the bounds of the array. at ConsoleApp.program.Main(String[]
args) line 87
BUT if i run in debug it works fine. Once i get it working on its own via the exe, i want to pass the filepath as a parameter in ssis.
see c# below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;
using System.IO;
namespace PDF_Read_ConsoleApp
{
class Program
{
public static void FilePath(string path)
{
//Console.WriteLine("Please enter full pdf path \n\n ");
//path = Console.ReadLine();
string fp;
fp = #path;
string[] files = Directory.GetFiles(path, "*.pdf");
foreach (string s in files)
{
string txtOutput = s.Replace(".pdf", ".txt");
if (File.Exists(txtOutput))
{
File.Delete(txtOutput);
}
string output;
PDDocument doc = null;
try
{
doc = PDDocument.load(s);
PDFTextStripper stripper = new PDFTextStripper();
stripper.getText(doc);
output = stripper.getText(doc);
StreamWriter NewFile;
NewFile = new StreamWriter(txtOutput);
//NewFile.Write(output.ToString());
NewFile.Write(output.ToString());
NewFile.Close();
}
finally
{
//if (doc != null)
//{
doc.close();
// Console.WriteLine("\n\n File saveed - ({0} ", txtOutput);
//}
}
}
}
static void Main(string[] args)
{
args[0] = #"C:\SSIS_Packages\PDF_Import\PDF_Import\PO_pdfs"; //// TESTING FILE PATH1
FilePath(args[0]);
}
}
}
Kind Regards
Rob
I have managed to get it working, I need to enter an argument within the debug screen, see information in URL below
Console app arguments, how arguments are passed to Main method
THank you for everyone's comments
I created the function pro:
it contains the process array
it calls another write function to make the file and write into it.
the write function writeproc:
it checks if the file at specified path is present or not.
if not it generates the file else it appends the text into the file.
when i run the code it is not doing anything.... :(
This is the main method for the console app that i have made in c#.
[STAThread]
static void Main(String[] args)
{
pro();
}
pro function:
static void pro()
{
Process[] localAll = Process.GetProcesses();
String path_pro = "C://KEYLOGS//processes.txt";
foreach(Process proc in localAll)
{
writeproc(path_pro, proc);
}
}
writeproc function:
static void writeproc(String p, Process the_process)
{
if (!File.Exists(p))
{
using (StreamWriter sw = File.CreateText(p))
{
//empty file generated.
}
}
else
{
using (StreamWriter sw = File.AppendText(p))
{
sw.WriteLine("Process: "+the_process);
}
}
}
This may be the cause of two different things.
1: The folder does not exist on your C drive so the file can't be created. (It will throw a System.IO.DirectoryNotFoundException)
Add Directory.CreateDirectory(p); to the start of your writeproc method.
2: You don't have enough rights to write to your C drive. (It will throw a System.UnauthorizedAccessException)
I suggest adding a breakpoint in your writeproc method to see what exception is being thrown.
I have a large directory of folders and files that contain a space at the end of the name, I'm trying to rename the directories with that space to one without, so that another application would be able to access it.
I'm using C# (but if there's a better option that would fix that issue please suggest) and here's my entire code:
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace removing_spaces_in_directories_names
{
class Program
{
public static string path = "../../../old_directory";
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(path);
WalkDirectoryTree(di);
Console.ReadLine();
}
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
if (root.Name != "old_directory")
{ renameDirectory(root); }
DirectoryInfo[] diArr = root.GetDirectories();
foreach(DirectoryInfo di in diArr)
{
WalkDirectoryTree(di);
}
}
static void renameDirectory(System.IO.DirectoryInfo dir)
{
Console.WriteLine("renaming: " + dir.FullName);
string newName = ReplaceLastOccurrence(dir.FullName, " ", "");
if (Directory.Exists(dir.FullName) == false)
{
//dir.MoveTo(newName);
String oldName = #"\\?\"+dir.FullName;
Directory.Move(oldName,newName);
}
}
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int place = Source.LastIndexOf(Find);
if (place == -1)
return Source;
string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
}
}
I have tried adding "\?\" to the beginning of the folder name as suggested here but that's not working, the error I'd get if I add it is: Illeagal characters in path.
On the other hand if I use dir.MoveTo(newName); without the "\?\" characters I'd get the error: Could not find a part of the path 'Volunteer Information '
How can I go through this if at all? would perhaps running this application on linux rather than windows help?
For each directory that you want to rename (remove the trailing space at the end in this case), let's say your DirectoryInfo variable is called di
You want to do this:
string oldName = di.FullName;
string newName = oldName.TrimEnd();
Directory.Move(oldName, newName);
I rewrote this in a PHP application that's sitting on linux and it worked.
I tried creating a program that tells you if a directory exists or not, but no matter what I input, it always comes up as not existing.
My Code:
using System;
using System.IO;
class TestFileAndDirectory
{
public static void Main()
{
string input;
input = Console.ReadLine();
if ( Directory.Exists(input))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't Exist");
}
Console.ReadLine();
}
}
At first I just thought maybe it was my logic, so I tried this code from the book: Microsoft Visual C# 2010: Comprehensive Ch.14:
using System;
using System.IO;
public class DirectoryInformation
{
public static void Main()
{
string directoryName;
string[] listOfFiles;
Console.Write("Enter a folder >> ");
directoryName = Console.ReadLine();
if(Directory.Exists(directoryName))
{
Console.WriteLine("Directory exists, " +
"and it contains the following:");
listOfFiles = Directory.GetFiles(directoryName);
for(int x = 0; x < listOfFiles.Length; ++x)
Console.WriteLine(" {0}", listOfFiles[x]);
}
else
{
Console.WriteLine("Directory does not exist");
}
}
}
When I tried this code it did not work either not even if I put it into the same base folder as the directory I'm trying to find.
Path in question: C:\C#\Chapter.14\Cat Haikus
Path of Program: C:\C#\Chapter.14\TestFilesAndDirectories.cs
The path parameter is permitted to specify relative or absolute path
information. Relative path information is interpreted as relative to
the current working directory.
Source: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
If your input string is only a folder name like "Chapter. 14" (relative path), then this folder must exist in the path of your executable file. Like PathOfTheExecutableFile\Chapter. 14.
If the folder is in a completely different place, use absolute paths. Like C:\Users\theuser\Desktop\Chapter. 14.
Update:
Since you want to check C:\C#\Chapter.14\Cat Haikus folder, you could check if it exists using
if (Directory.Exists(#"C:\C#\Chapter.14\Cat Haikus")){
Console.WriteLine("Exists");
}
I don't know your exact folder tree structure, but if your executable file is in a subfolder of C:\C#\Chapter.14\, you could also use Directoy.GetParent() method.
I'm just starting with a new product and I guess I don't understand the PATH variable. My documentation says to update the PATH like this which I do successfully in a little console application:
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff();
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
In the above project, I have a reference to HP.HPTRIM.SDK which exists at:
C:\Program Files\Hewlett-Packard\HP TRIM\HP.HPTRIM.SDK.dll
After the above ran successfully, I tried to permanently change the PATH by using Control Panel:System:Advanced:Environment Variables. I verified the above PATH by examining the registry at HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment. I see the following as the last entry in the PATH value:
;C:\Program Files\Hewlett-Packard\HP TRIM\
I thought this would permanently SET this at the end of the PATH but when I run the above console program with a few lines commented out I get the FileNotFoundException (see below). I am confused about how to get this in the PATH and not have to worry about it anymore.
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
//string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
//string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
//Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff(); // without setting the PATH this fails despite being in REGISTRY...
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
Only newly started processes that don't inherit their environment from their parent will have the updated PATH. You'll have to at least restart the Visual Studio hosting process, close and re-open your solution. To cover all possible corners, log out and log back in so that Windows Explorer (and thus Visual Studio) also start using the updated environment.