DirectoryNotFoundException was unhandled by user code? (Visual Studio 2013, C#) - c#

When I try to run this program, which writes details about a book to an xml file when a button is clicked, I get a DirectoryNotFoundException. How can I rewrite the address for my books.xml file under the App_Data folder?
Here are the details about the error.
An exception of type 'System.IO.DirectoryNotFoundException' occurred in System.Xml.dll but was not handled in user code
Additional information: Could not find a part of the path 'C:\App_Data\books.xml'.
Here is the Default.aspx code for reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace LibraryShelf
{
public partial class Default : System.Web.UI.Page
{
//protected void Page_Load(object sender, EventArgs e)
//{
//}
static void addNode(string fileName, XmlDocument xmlDoc)
{
XmlElement bookElement = xmlDoc.CreateElement("book");
bookElement.SetAttribute("name", "DotNet Made Easy");
XmlElement authorElement = xmlDoc.CreateElement("author");
authorElement.InnerText = "microsoft";
bookElement.AppendChild(authorElement);
XmlElement priceElement = xmlDoc.CreateElement("price");
priceElement.InnerText = "50";
bookElement.AppendChild(priceElement);
xmlDoc.DocumentElement.AppendChild(bookElement);
xmlDoc.Save(fileName);
}
protected void Button1_Click(object sender, EventArgs e)
{
string fileName = System.IO.Path.Combine(Request.ApplicationPath, "App_Data/books.xml");
XmlTextReader _xmlTextReader = new XmlTextReader(fileName);
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);
//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();
addNode(fileName, _xmlDocument);
}
}
}

The application folder is not the physical path to the web site, it's the path from the domain root to the application root. This is usually an empty string, unless you are using a virtual directory or an application subfolder on the server.
Use the MapPath method to get the physical path of a virtual address:
string fileName = Server.MapPath("~/App_Data/books.xml");

try this -
string path = System.IO.Path.GetFullPath(Server.MapPath("~/App_Data/books.xml"));
Server.MapPath will get you the location of the file.

Related

UWP SharpCompress Access Exception On Local Drives, Why?

I'm trying to use SharpCompress to read .rar files from my UWP application. It works fine on network shares from which I can read the archive no problem, but I get System.UnauthorizedAccessException on files anywhere on the local system including for instance USB drives. I have access to the files by other methods e.g. StorageFile. It makes no difference whether BroadFileSystemAccess is on or off. I've tried in both C# and Vb.net Here's the code of my test app in C#. The exception occurs at ArchiveFactory.Open.
I can also read Zip files no problem using the .net Compression methods but they can't do rar files, hence needing SharpCompress.
using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using SharpCompress;
using Windows.Storage.Pickers;
using Windows.Storage;
using SharpCompress.Archives;
namespace TestRAR
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
OpenRAR.Click += OpenRAR_Clicked;
}
public async void OpenRAR_Clicked(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".rar");
picker.FileTypeFilter.Add(".cbr");
picker.FileTypeFilter.Add(".cbz");
picker.FileTypeFilter.Add(".zip");
StorageFile pickfile = await picker.PickSingleFileAsync();
if (pickfile == null) { return; }
string pth = pickfile.Path;
FileInfo pickInfo = new FileInfo(pth);
try
{
ListRARs.Items.Clear();
using (var Arch = ArchiveFactory.Open(pickInfo))
{
foreach (IArchiveEntry a in Arch.Entries)
{
string thisKey = a.Key;
ListRARs.Items.Add(thisKey);
}
}
}
catch{ }
}
}
}
This is the first time I've used SharpCompress and I'm completely stumped. Any ideas anyone?

PdfLoadedDocument filenot found

I try to load a pdf document using PdfLoadedDocument method from Syncfusion.Pdf.WinForms NuGet package.
The code is pretty simple and look like this:
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(#"\\server\folder\sample.pdf");
But it raises file not found error.
You may:
Test manually if the file is here: open your file explorer and enter the path, does the file open ?
Test programmatically if the file is here: Put File.Exists(#"\\server\folder\sample.pdf") in your code. This may raise other issues (like access denied that the PdfLoadedDocument may have swallowed).
Edit:
If you take a look to de-compiled code of PdfLoadedDocument (from Syncfusion.Pdf.WinForms v17.4.0.46 NuGet package) it is:
public PdfLoadedDocument(string filename)
: this(PdfLoadedDocument.CreateStream(filename))
{
this.isDispose = true;
this.m_bCloseStream = true;
this.m_fileName = filename;
}
The PdfLoadedDocument.CreateStream code is:
if (filename == null)
throw new ArgumentNullException(nameof (filename));
if (!File.Exists(filename))
throw new ArgumentException("File doesn't exist", nameof (filename));
...
So the "File doesn't exist" exception occurs when File.Exists return false.
If you take a look to File.Exists documentation:
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
The file may be there but your program may not have the right to access it.
Anyway, I tested PdfLoadedDocument(#"\\server\users\Orace\test.pdf"); where I have full access to \\server\users\Orace, and it works fine.
https://help.syncfusion.com/cr/file-formats/Syncfusion.Pdf.Parsing.PdfLoadedField.html
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing; //<================
namespace Text_Extraction
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (PdfDocument document = new PdfDocument())
{
// Load an existing PDF document.
PdfLoadedDocument loadedDocument = new
PdfLoadedDocument(#"C:\Users\grayg\Documents\Text To Speech
Stuff\NationalTreeClimbingGuide2015April.pdf");
// Loading page collections

C# Console app need assistance with main args error

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

COMException when converting OneNote into HTML (but it works for PDF)

I am trying to convert a OneNote section into HTML and keep running into a persistent error. It's weird because the same code works if I convert to PDF. I'd appreciate help wit this one.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using OneNote = Microsoft.Office.Interop.OneNote;
using Office = Microsoft.Office.Core;
namespace trial
{
class Class1
{
[STAThread]
static int Main(string[] args)
{
String strXML;
OneNote.Application onApplication = new OneNote.Application();
onApplication.GetHierarchy(null,OneNote.HierarchyScope.hsPages, out strXML);
XDocument doc = XDocument.Parse(strXML);
XNamespace ns = doc.Root.Name.Namespace;
foreach (var sectionNode in from node in doc.Descendants(ns+"Section") select node)
{
string id = sectionNode.Attribute("ID").Value;
string path = "C:\\elixir.html";
if (id == "some specific ID")
{
//confirmed that it reaches this point
try
{
onApplication.Publish(id, path, OneNote.PublishFormat.pfHTML, ""); //PDF conversion Works! But HTML doesn't.
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
return 0;
}
}
}
Here are my references. All "Embed Interop Types" settings have been set to False.
Here is the exception message
A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in Microsoft.Office.Interop.OneNote.dll
Exception from HRESULT: 0x8004201A
I checked that this error is a "file already exists" error, but that's wrong. The destination file is definitely not present as program commences running.
Changing the extension from
string path = "C:\\elixir.html";
to
string path = "C:\\elixir.htm";
fixed it.

C# Web Reference and PHP

I am attempting to call a Web Service (created in PHP) from my C# application. I have successfully added the Web Reference in Visual Studios, however I cannot figure out exactly how to invoke the call to the web service. I have been following this tutorial: http://sanity-free.org/article25.html however when I try and compile I get a "The type or namespace name 'SimpleService' could not be found". My C# code is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace inVision_OCR
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void translateButton_Click(object sender, EventArgs e)
{
// We need to snap the image here somehow . . .
// Open up the image and read its contents into a string
FileStream file = new FileStream("\\Hard Disk\\ocr_images\\test.jpg", FileMode.Open);
StreamReader sr = new StreamReader(file);
string s = sr.ReadToEnd();
sr.Close();
// Using SOAP, pass this message to our development server
SimpleService svc = new SimpleService();
string s1 = svc.getOCR("test");
MessageBox.Show(s);
}
}
}
The SimpleService is probably in a different namespace, look at the properties of the web reference you added and see what namespace the proxy class SimpleService is being generated in, then add a using statement in your code to reference that namespace.

Categories

Resources