miércoles, 28 de marzo de 2012

Crear y leer Archivos Dynamics ax 2012

static void Job_File_IO_TextIo_Write_Read(Args _args)
{
    TextIo txIoRead,
         txIoWrite;
    FileIOPermission fioPermission;
    container containFromRead;
    int xx,
        iConLength;
    str sTempPath,
        sFileName = "Test_File_IO.txt",
        sOneRecord;
    ;
    // Get the temporary path.
    sTempPath = WINAPI::getTempPath();
    info("File is at: " + sTempPath + sFileName);

    // Assert permission.
    fioPermission = new FileIOPermission
        (sTempPath + sFileName ,"RW");
    fioPermission.assert();
 
    // If the test file already exists, delete it.
    if (WINAPI::fileExists(sFileName))
    {
        WINAPI::deleteFile(sTempPath + sFileName);
    }
    
    // Open a test file for writing.
    // "W" mode overwrites existing content, or creates the file.
    txIoWrite = new TextIo( sTempPath + sFileName ,"W");

    // Write records to the file.
    txIoWrite.write("Hello        World.");
    txIoWrite.write("The sky is blue.");
    txIoWrite.write("");
    txIoWrite.write("// EOFile");

    // Close the test file.
    txIoRead = null;

    // Open the same file for reading.
    txIoRead = new TextIo(sTempPath + sFileName ,"R");
    // Read the entire file into a container.
    containFromRead = txIoRead.read();

    // Loop through the container of file records.
    while (containFromRead)
    {
        sOneRecord = "";
        iConLength = conLen(containFromRead);
        // Loop through the token in the current record.
        for (xx=1; xx <= iConLength; xx++)
        {
            if (xx > 1) sOneRecord += " ";
            sOneRecord += conPeek(containFromRead ,xx);
        }
        info(sOneRecord);

        // Read the next record from the container.
        containFromRead = txIoRead.read();
    }

    // Close the test file.
    txIoRead = null;
    // Delete the test file.
    WINAPI::deleteFile(sTempPath + sFileName);

    // revertAssert is not really necessary here,
    // because the job (or method) is ending.
    CodeAccessPermission::revertAssert();
}
Fuente: http://msdn.microsoft.com/en-us/library/cc967403.aspx

7 comentarios:

  1. Hola Omar, gracias por la info, muy ilustrativo. No sabes cómo modificar un archivo de texto en una línea especifica? Saludos

    ResponderEliminar
  2. hola, gracias por el post. Me gustaria saber si el archivo es csv, delimitado por coma. Necesito saber en esa primera linea como dividir las columnas para poder asignarlas a diferentes variables.

    Espero haberme explicado. Gracias.

    ResponderEliminar
    Respuestas
    1. Hola que tal seria algo mas o menos como esto

      CommaTextIo commaTextIo;
      FileIOPermission permission;
      container containFromRead;
      int x;
      str var1;
      str var2;
      int row;
      #File
      ;

      permission = new FileIOPermission('nombrearchivo',#io_read);
      permission.assert();

      commaTextIo = new CommaTextIO('nombrearchivo','R');
      commaTextIo.inFieldDelimiter(',');//Separar por un caractar
      containFromRead = commaTextIo.read();
      While(containFromRead)
      {

      if(row == 1) //Leer psar encabezado por si tiene
      {
      containFromRead = commaTextIo.read(); //siguiente renglon
      row++;
      continue;
      }
      ///Leer n Columnas
      var1 = conPeek(containFromRead,1);
      var2 = conPeek(containFromRead,2);

      containFromRead = commaTextIo.read(); //siguiente renglon
      row++;
      }
      commaTextIo = null;

      Eliminar
  3. hola buen dia disculpa ¿sabes como podria leer varios archivos que estan en una misma ruta ?

    ResponderEliminar
    Respuestas
    1. Hola que tal puedes utilizar este código para recorrer todos los archivos.

      System.String[] files;
      System.Collections.IEnumerator enumerator;
      str file;
      try
      {
      fileSet = new Set(Types::Container);

      files = System.IO.Directory::GetFiles(filePath, '*.txt');

      enumerator = files.GetEnumerator();

      while(enumerator.MoveNext())
      {

      file = enumerator.get_Current();
      fileSet.add([file]); /Aqui esta la ura de cada archivo de el Path y ya se puede utilizar para abrirlo y leerlo

      }

      }
      catch(Exception::Internal)
      {

      this.processCLRErrorException();

      }

      catch(Exception::CLRError)
      {
      this.processCLRErrorException();

      }



      Eliminar
  4. Hola buen día, disculpa una pregunta ¿Como puedo leer al ruta de una carpeta, verificar si existen archivos y leer el contenido de la carpeta, copiar el nombre de cada archivo a una tabla y eliminar el archivo después de copiar el nombre del archivo a la tabla?

    ResponderEliminar
  5. //Te sirve para leer la ruta de la carpeta
    folder = winapi::browseForPath(0,'Carpeta');
    //Otra opcion para leer la Carpeta te da la opcion de crear carpeta
    folder = WinAPI::browseForFolderDialog("Seleccionar Carpeta");
    //Verificar si existe archivo
    if (WINAPI::fileExists(filePath + sfileName))
    { //Archivo Existe }
    else
    { //puedes crear el archivo }

    //
    //Debes declarar el filtro de tipo de archivos en este ejemplo Txt
    container conFilter=["TXT","*.txt"];
    sfilePathAndName=WinAPI::getSaveFileName(0,conFilter,folder,'Guardar Como','Txt','',2);

    ResponderEliminar