Acceso denegado a la ruta de acceso C# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
//English
Im newbie coding... i want to edit some text files in this path D:.
The problem is if one text file has been used my app throw error saying "Access Denied"...
I want to skip that error and continue with the next file... help me please...
Suppose the file United3.txt throw access denied and i cant edit.
//Español
Soy nuevo programador y quiero editar varios archivos de texto en un disco duro D.
El problema es que si uno esta siendo usado me dice acceso denegado por ende quiero omitir la edicion a el y que siga con el proximo archivo.
Este es mi método.
public void startAction3()
{
string DiscoDuroD = "D:\\";
if (Directory.Exists(DiscoDuroD))
{
string text = "Hello My Friend";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United3.txt"), true))
{
outputFile.WriteLine(text);
}
string text2 = "EYY";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United4.txt"), true))
{
outputFile.WriteLine(text);
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco Duro D no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}

(Hola GBY)
You should capture Exception and proceed with the next file.
Find below an example.
More info about try-catch structure --> https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/keywords/try-catch
De nada!
public void startAction3()
{
string DiscoDuroD = "D:\\";
if (Directory.Exists(DiscoDuroD))
{
string text = "Hello My Friend";
try
{
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United3.txt"), true))
{
outputFile.WriteLine(text);
}
}
catch (IOException ex)
{
// do something in case any error occurs, leave a trace or write a console warning...
console.WriteLine("Error fichero United3: "+ ex.Message)
}
string text2 = "EYY";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United4.txt"), true))
{
outputFile.WriteLine(text);
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco Duro D no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}

Perdon por la falta de puntuacion y cualquier error de espanol. Hace un tiempo sin usar espanol con regularidad.
Sorry for the lack of punctuation and mistakes in my Spanish. It's been a while since I used Spanish regularly.
Si tu programa tiene que procesar varios archivos en una manera igual, podrias implementar un metodo asi con 'try-catch' igual que el respuesta de David:
If your application has to process several files in a similar way, you could implement a method like this with a 'try-catch' block similar to David's answer:
public void OutputToFile(string discPrefix, string fileName, string text)
{
if (Directory.Exists(discPrefix))
{
try
{
using (StreamWriter outputFile = new StreamWriter(Path.Combine(discPrefix,
fileName), true))
{
outputFile.WriteLine(text);
}
}
catch (IOException ex)
{
// do something in case any error occurs, leave a trace or write a console warning...
console.WriteLine("Error fichero" + fileName + ": " + ex.Message)
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
...y usarlo entre StartAction3 asi:
...and call it from within your StartAction3 like this:
OutputToFile("D://", "United3.txt", "Hello my friend");
OutputToFile("D://", "United4.txt", "EYY");

Related

Can't log string using NLOG

I can't log a string from an HTTP request using NLOG. Here's the code:
HttpResponseMessage res = client.PostAsync(path, content).Result;
if (!res.IsSuccessStatusCode)
{
if (File.Exists(tempFilePath))
File.Delete(tempFilePath);
String responseStr = res.Content.ReadAsStringAsync().Result;
//TODO(nassim) : Remplacé ce try catch par juste un retour d'erreur dans les log
//ErrorReponse error = JsonConvert.DeserializeObject<ErrorReponse>(responseStr);
Logger.Debug("Taille du log : " + responseStr.Length);
if(responseStr.Length > 200)
{
Logger.Debug(" 1");
Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 200));
}
else
{
Logger.Debug(" 2");
Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 10));
}
if (responseStr.Contains("Invalid credentials.") || responseStr.Contains("Token is expired."))
{
refreshToken(vault, storedValues);
storeDocInReciTAL(env);
}
throw new Exception("Erreur d'envoi du document vers reciTAL.");
And here's the stacktrace:
As you can see, the line concatening with the responseStr doesn't show anywhere. At first I thought it was because the string was too long, but it's only 37 characters.
What am I doing wrong?
Using structured logging resolves the problem. I don't understand why it doesn't work with a simple concatenation.

How do I delete a row from a gridview and SQL using a webservice?

I want to be able to delete a row from a gridview when I click on a delete button. But for some reason, the code only deletes the rows from the gridview but not the from the SQL DataBase.
It's because i'm not using the web method eliminarTarea correctly?
What am I doing wrong? Many Thanks!
button method
try
{
if (MessageBox.Show("¿Está seguro de querer eliminar esta nota?","Message",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
{
int rows = DataGVTareas.RowCount;
for(int i = rows - 1; i >= 0; i--)
{
if (DataGVTareas.Rows[i].Selected)
{
ServiceMantenedorCliente.WebServiceMantenedorClienteSoapClient auxNegocio = new ServiceMantenedorCliente.WebServiceMantenedorClienteSoapClient();
auxNegocio.webEliminarTarea(titulotareasDataGridViewTextBoxColumn.ToString());
tareasBindingSource.RemoveAt(DataGVTareas.Rows[i].Index);
}
}
}
//ServiceMantenedorCliente.WebServiceMantenedorClienteSoapClient auxNegocio = new ServiceMantenedorCliente.WebServiceMantenedorClienteSoapClient();
if (String.IsNullOrEmpty(this.DataGVTareas.ToString()))
{
MessageBox.Show("No hay datos por eliminar ", "NoteIt", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
//auxNegocio.webEliminarCliente(DataGVTareas.Rows[i]);
MessageBox.Show("Los datos han sido eliminados", "NoteIt", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Se ha producido un error inesperado, por favor reinicie la aplicación e intente nuevamente" + ex.Message, "NoteIt", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
app code
public void eliminarTarea(String titulo_tareas)
{
this.ConexionTareas();
this.Conec1.CadenaSQL = "DELETE FROM " + this.Conec1.NombreTabla
+ " WHERE titulo_tareas = '" + titulo_tareas + "';";
this.Conec1.EsSelect = false;
this.Conec1.Conectar();
}
webservice method
[WebMethod]
public void webEliminarTarea(String titulo_tareas)
{
NegocioNotas auxNegocio = new NegocioNotas();
auxNegocio.eliminarCliente(titulo_tareas);
}
I don't read spanish so I hope I get the gist of how your controls are wired up... where do you call the .EndEdit() for the BindingSource which actually writes back to the database?
Also, as #Larnu mentioned, fix your SQL query:
public void eliminarTarea(String titulo_tareas)
{
this.ConexionTareas();
//You'll have to fix this up because I don't know what "Conec1" is.
//This demonstrates putting your text values into a parameter instead
//of string concatenation.
//Concatenation of NombreTabla is also a vulnerability but I don't know how to fix that one
//because it is a table name and I don't know where NobreTabla is sourced from.
string sqlTxt = "DELETE FROM " + this.Conec1.NombreTabla
+ " WHERE titulo_tareas = #TituloTareas;";
SqlCommand cmd = new SqlCommand([sqlConnection here], sqlTxt);
cmd.Parameters.AddWithValue("#TituloTareas", titulo_tareas);
this.Conec1.SqlCommand = cmd; //Does this even work with Conec1?
this.Conec1.EsSelect = false;
this.Conec1.Conectar();
}

Improving with Array instead of IF

I would like to use an Array instead of IF, I think that is more efficient but I don't how exactly do it sorry, I am new in C#, can someone just give me an good example please? I have a lot of Cliente.Contains and I think "If" is not the correct way, this is the code:
if (Cliente.Contains("0003919026"))
{
nombreCliente = "TELMOV";
}
if (Cliente.Contains("0002402248"))
{
nombreCliente = "Workplay S.A. DE C.V.";
}
if (Cliente.Contains("0009206605"))
{
nombreCliente = "SISTEMAS Y SERVICIOS DE (SYSCOM)";
}
CadenaRes = "Se proceso el archivo el dia " + DateTime.Now.ToString() + "\n" + "El archivo con nombre: " + nombreCliente;
Console.WriteLine("Carga Satisfactoria: {0} ", transfer.FileName);
I think you can achieve your task using Dictionary like following:
var dic = new Dictionary<string, string>();
dic.Add("0003919026", "TELMOV");
dic.Add("0002402248", "Workplay S.A. DE C.V.");
dic.Add("0009206605", "SISTEMAS Y SERVICIOS DE (SYSCOM)");
dic.Add("0009206605", "Se proceso el archivo el dia" + DateTime.Now.ToString() + "\n" + "El archivo con nombre: " + nombreCliente);
nombreCliente = dic.FirstOrDefault(x => Cliente.contains(x));
You can also use list of a class containing your key and value. Then use linq to get your required value.
Technically, you can organize substitution pairs (what to find and what to show) into a collection, say an array and implement something like this:
using System.Linq;
...
string nombreCliente = ...
(string find, string show)[] subs = new[] {
("0009206605", "SISTEMAS Y SERVICIOS DE (SYSCOM)"),
("0002402248", "Workplay S.A. DE C.V."),
//TODO: Add more pairs here
};
// Reverse: according to the code in the question, the later pair should prevail;
// if it's not possible we can drop .Reverse()
foreach (var pair in subs.Reverse())
if (Cliente.Contains(pair.find)) {
nombreCliente = pair.show;
break;
}
CadenaRes = string.Join(Environment.NewLine,
$"Se proceso el archivo el dia {DateTime.Now}",
$"El archivo con nombre: {nombreCliente}",
);
Console.WriteLine($"Carga Satisfactoria: {transfer.FileName}");
But I doubt in underlying logic: we are looking for just a fragment, and the assign nombreCliente;
what if Cliente is combined, say 0009206605 and (0002402248)?

couldnt find the path in merging pdf files in one single pdf document

im trying in c# to merge 2 pdf in a single one using the pdfsharp library, it shows an error that it couldnt find the path in the path where im going to save it, this is where i put my paths
string directorio = #"C:\Users\Usuario\Documents\PDF\";//Directorio donde buscara los archivos pdf
string destino = #"C:\Users\Usuario\Documents\Prueba\";//Directorio donde estara el archivo unido
string[] archivo = Directory.GetFiles(directorio);
Unir(destino, archivo);
if (MessageBox.Show("Espere un momento mientras su solicitud es procesada", "INFORMACION" + MessageBoxButtons.OK + MessageBoxIcon.Information) == DialogResult.OK)
{
MessageBox.Show("Su documento se ha unido con exito, fue enviado a la direccion: " + destino);
}
this is where my merge method
private void Unir(string outfilePath , string[] pdfFiles){
PdfDocument documento = new PdfDocument();
foreach(string pdfFile in pdfFiles)
{
PdfDocument inputDocumento = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
documento.Version = inputDocumento.Version;
foreach(PdfPage page in inputDocumento.Pages)
{
documento.AddPage(page);
}
documento.Options.CompressContentStreams = true;
documento.Options.NoCompression = false;
documento.Save(outfilePath);
}
}
A file name is needed to save a PDF file, not a folder.
The Save should be made after the foreach loop to save only once.

It's posible print PDF when PDF is open in memorystream?

Its posible open print dialog when is open in memorystram?
Actually I save the pdf in "~/App_Data/Rep_PDF/" and after show a pdf in an iframe but I cant do it because I recive a message :
"Not allowed to load local resource: file:///C:/Users/andres.martinez/Documents/TFS%20Monterrey%20Gob/InterfaceMonterrey%20PROD/Interface%20Monterrey%20PROD/InterfaceMonterrey/App_Data/Rep_PDF/Copia_C_Administrativa%2030-04-2019.pdf"
Could you help me How to print a pdf in asp mvc?
this is part of my code:
public ActionResult ImprimeReporte()
{
//Indicamos donde vamos a guardar el documento
string directorioRaiz = "~/App_Data/Rep_PDF/";
string NombreArchivoPDF = "C_Administrativa " + DateTime.Today.ToString("dd-MM-yyyy") + ".pdf";
string path_Original=Server.MapPath(directorioRaiz+NombreArchivoPDF);
string path_Copia = Server.MapPath(directorioRaiz + "Copia_"+NombreArchivoPDF);
if (System.IO.File.Exists(path_Original))
{
//SI EXISTE EL ARCHIVO EN LA CARPETA, LO MANDA A IMPRIMIR
Inicia_PrintScript(path_Original, path_Copia);
ViewData["path_Copia"] = path_Copia;
//Elimina los archivos , despues de que se imprimio
// System.IO.File.Delete(path_Original);
//System.IO.File.Delete(path_Copia);
}
else
{
//SI NO EXISTE MANDA LLAMAR AL METODO PARA DESCARGAR EL ARCHIVO Y DESPUES IMPRIMIRLO
Genera_Pdf_Administrativo();
Inicia_PrintScript(path_Original, path_Copia);
ViewData["path_Copia"] = path_Copia;
//Elimina los archivos , despues de que se imprimio
//System.IO.File.Delete(path_Original);
//System.IO.File.Delete(path_Copia);
}
return View();
}
second part
public static void Inicia_PrintScript(string Original, string Copia)
{
PdfReader reader = new PdfReader(Original);
PdfStamper stamper = new PdfStamper(reader, new FileStream(Copia, FileMode.Create));
AcroFields fields = stamper.AcroFields;
stamper.JavaScript = "this.print(true);\r";
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
View
<iframe src="#ViewData["path_Copia"].ToString()" id="myFrame" frameborder="0" style="border:0;" width="700" height="300"></iframe>
Well, it's possible to open a PDF with print dialog in another tab.
In your controller you need to get the file in memory just to return it, or generate the file on fly.
public FileResult PDFToReturn()
{
string filePath = Server.MapPath("Path_to_PDF");
return File(System.IO.File.ReadAllBytes(filePath), System.Web.MimeMapping.GetMimeMapping(filePath));
}
javascript does the magic.
function printPDF() {
let link = 'javascript:w=window.open("/Controller/PDFToReturn"); w.print();';
location.href = link;
}

Categories