Хутка & Лёгка: Пераназавіце загружаны файл з дапамогай аб'ектнай мадэлі SharePoint праз прыёмнік падзей

АБНАЎЛЕННЕ: This works but there are significant limitations which are described in the comments. This may still be useful in some cirumstances.

АБНАЎЛЕННЕ 2: У маім бягучым праекце, users always upload documents. У выніку, 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() Прыёмнік шукае сапраўднае значэнне там да фактычнага выканання перайменавання і з тых часоў, 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()" метад. Замест, мы выкарыстоўваем "MoveTo(…)". Here is a minimal bit of code to accomplish this:

 грамадскасць адмяняць ануляваць ItemAdded(SPItemEventProperties ўласцівасці)
        {
            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.

Гэта больш карысна версія, якая робіць тое ж самае, but assigns the name of the file to "Title":

 грамадскасць адмяняць ануляваць ItemAdded(SPItemEventProperties ўласцівасці)
        {
            DisableEventFiring();

            // Назначце назва гэтага пункта на імя самога файла.
 // УВАГА: Гэта прызначэнне павінна адбыцца, перш чым змяніць сам файл.
 // Выклік абнаўлення() на SPFile здаецца несапраўдным ўласцівасці ў
 // пэўным сэнсе.  Updates to "Title" не ўдалося пакуль што змены (і абнаўлення() называць)
 // былі перамешчаныя перад змяненнем імя файла.
            properties.ListItem["Title"] = Properties.ListItem.File.Name;

            properties.ListItem.Update();

            SPFile F = properties.ListItem.File;

            // Атрымаць пашырэння файла.  Нам трэба, каб пазней.
 радок spfileExt = новы Інфармацыя аб файле(f.Name).Пашырэнне;

            // Пераназавіце файл у ID элемента спісу і выкарыстоўваць пашырэнне файла, каб захаваць
 // што частка яго ў такім выглядзе.
            f.MoveTo(properties.ListItem.ParentList.RootFolder.Url +
                "/" + properties.ListItem["ID"] + spfileExt);

            // Фіксацыя ходу.
            f.Update();

            EnableEventFiring();
        }

4 думкі пра «Хутка & Лёгка: Пераназавіце загружаны файл з дапамогай аб'ектнай мадэлі SharePoint праз прыёмнік падзей

  1. Без назвы
    Таксама, Калі вы робіце гэта з слоў, ён будзе вяртаць памылку і сказаць файл не існуе. Ён не расказаў пра новыя URL. Я яшчэ не знайшоў спосаб абыйсці гэтую.
  2. Paul Galvin
    Thanks for pointing that out. I don’t know an answer to that one either … Будзе цікава паглядзець, як ім кіраваць.
    RE: асінхронны & перанакіраваньні
    I wonder if moving it to an ItemAdding will solve it. That’s a big hole.
    Дзякуй!
    –Пол
  3. Надим Mitha
    Паколькі файл пераносіцца асінхронна, ёсць магчымасць перанакіраваны на EditForm.aspx да пераезду імкнецца (і гэта дрэнна). 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.

Пакінуць каментар да Надим Mitha адмяніць адказ

Ваш электронны адрас не будзе апублікаваны. Абавязковыя палі пазначаныя * *