Rápido & Fácil: Renomear o ficheiro cargado empregando SharePoint obxecto Model a través dun receptor de eventos

Actualización: This works but there are significant limitations which are described in the comments. This may still be useful in some cirumstances.

Actualización 2: O meu proxecto actual, users always upload documents. Como resultado, I don’t run into a problem where MS Word is running and thinks that the file was renamed on it. I did run into a problem, "the file was modified by someone else" and solved this via a simple semaphore type flag. Users need to change a meta data field from its default value to something else. The itemupdated() receptor busca por un valor válido alí antes de realmente facer a renomeação e desde entón, I have not had any problems. Your mileage may vary.

I have a client requirement to change the name of files uploaded to a specific document library to conform with a particular naming convention. The API does not provide a "rename()" método. Pola, usan "MoveTo(…)". Here is a minimal bit of code to accomplish this:

 público substituír invalidar ItemAdded(SPItemEventProperties Propiedades)
        {
            SPFile f = properties.ListItem.File;

            f.MoveTo(properties.ListItem.ParentList.RootFolder.Url + "/xyzzy.doc");
            f.Update();

        }

The only tricky bit is the "properties.ListItem.ParentList.RootFolder.Url". The MoveTo() method requires a URL. That mashed up string points me to the root folder of my current document library. This allows me to avoid any hard coding in my event receiver.

Esta é unha versión máis útil que fai o mesmo, but assigns the name of the file to "Title":

 público substituír invalidar ItemAdded(SPItemEventProperties Propiedades)
        {
            DisableEventFiring();

            // Asignar o título deste artigo para o nome do ficheiro en si.
 // NOTA: Esta asignación debe ocorrer antes de modificar o propio arquivo.
 // Chamando actualización() no SPFile parece invalidar as propiedades en
 // nalgún sentido.  Updates to "Title" puido ata que o cambio (e actualización() chamar)
 // foron movidos fronte á mudanza do nome do ficheiro.
            properties.ListItem["Title"] = Properties.ListItem.File.Name;

            properties.ListItem.Update();

            SPFile f = properties.ListItem.File;

            // Obter a extensión do ficheiro.  Necesitamos que máis tarde.
 corda spfileExt = novo FileInfo(f.Name).Extensión;

            // Renomeie o ficheiro para a identificación do elemento da lista e utilizar a extensión do ficheiro para manter
 // que parte dela intacta.
            f.MoveTo(properties.ListItem.ParentList.RootFolder.Url +
                "/" + properties.ListItem["ID"] + spfileExt);

            // Comprometer o movemento.
            f.Update();

            EnableEventFiring();
        }

4 pensamentos sobre "Rápido & Fácil: Renomear o ficheiro cargado empregando SharePoint obxecto Model a través dun receptor de eventos

  1. Ningún nome
    Tamén, If you do this from within Word, it will return an error and say the file does not exist. It is not told about the new URL. I have not yet found a way around this.
    Responder
  2. Paul Galvin
    Thanks for pointing that out. I don’t know an answer to that one either … will be interesting to see how to manage it.
    RE: async & redirection
    I wonder if moving it to an ItemAdding will solve it. That’s a big hole.
    Grazas!
    –Galicia
    Responder
  3. Nadeem Mitha
    Because the file gets moved asynchronously, there is a possibility of being redirected to EditForm.aspx before the move is committed (and that’s bad). You’ll see that this happens if you make the code sleep before the MoveTo line. I still haven’t figured out what can be done about that problem aside from using a customized edit form.
    Responder

Deixe unha resposta

Enderezo de correo electrónico non será publicado. Os campos obrigatorios están marcados *